forge-sql-orm-cli 2.1.11 → 2.1.13
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 +44 -8
- package/dist-cli/cli.js +5 -0
- package/dist-cli/cli.js.map +1 -1
- package/dist-cli/cli.mjs +5 -0
- package/dist-cli/cli.mjs.map +1 -1
- package/dist-cli/forgeSqlOrmCLI.js.map +1 -1
- package/dist-cli/forgeSqlOrmCLI.mjs +3 -3
- package/dist-cli/forgeSqlOrmCLI.mjs.map +1 -1
- package/package.json +20 -13
- package/src/actions/generate-models.ts +7 -0
- package/tsconfig.json +2 -2
- /package/dist-cli/{forgeSqlOrmCLI.d.ts → forgeSqlOrmCLI.d.mts} +0 -0
- /package/src/{forgeSqlOrmCLI.ts → forgeSqlOrmCLI.mts} +0 -0
package/README.md
CHANGED
|
@@ -8,8 +8,6 @@
|
|
|
8
8
|
[](https://github.com/vzakharchenko/forge-sql-orm/actions/workflows/node.js.yml)
|
|
9
9
|
[[](https://deepscan.io/dashboard#view=project&tid=26652&pid=29272&bid=940614)
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
13
11
|
A command-line interface tool for managing Atlassian Forge SQL migrations and model generation with Drizzle ORM integration.
|
|
14
12
|
|
|
15
13
|
## About
|
|
@@ -26,10 +24,28 @@ A command-line interface tool for managing Atlassian Forge SQL migrations and mo
|
|
|
26
24
|
|
|
27
25
|
## Installation
|
|
28
26
|
|
|
27
|
+
The CLI tool must be installed as a local development dependency and used via npm scripts:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
npm install forge-sql-orm-cli -D
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
# Basic installation for UI-Kit projects
|
|
34
|
+
|
|
35
|
+
npm install forge-sql-orm-cli -D --legacy-peer-deps
|
|
36
|
+
|
|
37
|
+
### Setup npm Scripts
|
|
38
|
+
|
|
39
|
+
Add the following scripts to your `package.json`:
|
|
40
|
+
|
|
29
41
|
```bash
|
|
30
|
-
npm
|
|
42
|
+
npm pkg set scripts.models:create="forge-sql-orm-cli generate:model --output src/entities --saveEnv"
|
|
43
|
+
npm pkg set scripts.migration:create="forge-sql-orm-cli migrations:create --force --output src/migration --entitiesPath src/entities"
|
|
44
|
+
npm pkg set scripts.migration:update="forge-sql-orm-cli migrations:update --entitiesPath src/entities --output src/migration"
|
|
31
45
|
```
|
|
32
46
|
|
|
47
|
+
**Note:** The CLI tool is designed to work as a local dependency through npm scripts. Configuration is saved to `.env` file using the `--saveEnv` flag, so you only need to provide database credentials once.
|
|
48
|
+
|
|
33
49
|
## Available Commands
|
|
34
50
|
|
|
35
51
|
### Generate Models
|
|
@@ -41,6 +57,7 @@ forge-sql-orm-cli generate:model [options]
|
|
|
41
57
|
```
|
|
42
58
|
|
|
43
59
|
Options:
|
|
60
|
+
|
|
44
61
|
- `--saveEnv` - Save the configuration to a `.env` file
|
|
45
62
|
- `--host` - Database host (default: localhost)
|
|
46
63
|
- `--port` - Database port (default: 3306)
|
|
@@ -51,6 +68,7 @@ Options:
|
|
|
51
68
|
- `--versionField` - Name of the version field (default: version)
|
|
52
69
|
|
|
53
70
|
The generated models will include:
|
|
71
|
+
|
|
54
72
|
- Drizzle table definitions compatible with Atlassian Forge SQL
|
|
55
73
|
- TypeScript types for your database schema
|
|
56
74
|
- Version metadata for tracking schema changes
|
|
@@ -64,6 +82,7 @@ forge-sql-orm-cli migrations:create [options]
|
|
|
64
82
|
```
|
|
65
83
|
|
|
66
84
|
Options:
|
|
85
|
+
|
|
67
86
|
- `--saveEnv` - Save the configuration to a `.env` file
|
|
68
87
|
- `--host` - Database host (default: localhost)
|
|
69
88
|
- `--port` - Database port (default: 3306)
|
|
@@ -83,6 +102,7 @@ forge-sql-orm-cli migrations:update [options]
|
|
|
83
102
|
```
|
|
84
103
|
|
|
85
104
|
Options:
|
|
105
|
+
|
|
86
106
|
- `--saveEnv` - Save the configuration to a `.env` file
|
|
87
107
|
- `--host` - Database host (default: localhost)
|
|
88
108
|
- `--port` - Database port (default: 3306)
|
|
@@ -101,6 +121,7 @@ forge-sql-orm-cli migrations:drop [options]
|
|
|
101
121
|
```
|
|
102
122
|
|
|
103
123
|
Options:
|
|
124
|
+
|
|
104
125
|
- `--saveEnv` - Save the configuration to a `.env` file
|
|
105
126
|
- `--host` - Database host (default: localhost)
|
|
106
127
|
- `--port` - Database port (default: 3306)
|
|
@@ -137,6 +158,7 @@ This CLI tool is designed to work seamlessly with Atlassian Forge SQL and Drizzl
|
|
|
137
158
|
## Environment Variables
|
|
138
159
|
|
|
139
160
|
The CLI supports loading configuration from environment variables. You can either:
|
|
161
|
+
|
|
140
162
|
1. Use the `--saveEnv` flag to save your configuration to a `.env` file
|
|
141
163
|
2. Create a `.env` file manually with the following variables:
|
|
142
164
|
|
|
@@ -153,26 +175,40 @@ FORGE_SQL_ORM_VERSION_FIELD=version
|
|
|
153
175
|
|
|
154
176
|
## Examples
|
|
155
177
|
|
|
178
|
+
### Setup
|
|
179
|
+
|
|
180
|
+
First, install the CLI and setup npm scripts:
|
|
181
|
+
|
|
182
|
+
```bash
|
|
183
|
+
npm install forge-sql-orm-cli -D
|
|
184
|
+
npm pkg set scripts.models:create="forge-sql-orm-cli generate:model --output src/entities --saveEnv"
|
|
185
|
+
npm pkg set scripts.migration:create="forge-sql-orm-cli migrations:create --force --output src/migration --entitiesPath src/entities"
|
|
186
|
+
npm pkg set scripts.migration:update="forge-sql-orm-cli migrations:update --entitiesPath src/entities --output src/migration"
|
|
187
|
+
npm pkg set scripts.migration:drop="forge-sql-orm-cli migrations:drop --entitiesPath src/entities --output src/migration"
|
|
188
|
+
```
|
|
189
|
+
|
|
156
190
|
### Generate Drizzle Models for Atlassian Forge SQL
|
|
157
191
|
|
|
158
192
|
```bash
|
|
159
|
-
|
|
193
|
+
npm run models:create
|
|
160
194
|
```
|
|
161
195
|
|
|
196
|
+
On first run, you'll be prompted for database credentials (host, port, user, password, dbName). These will be saved to `.env` file for subsequent runs.
|
|
197
|
+
|
|
162
198
|
This will generate Drizzle table definitions and TypeScript types compatible with Atlassian Forge SQL in the specified output directory.
|
|
163
199
|
|
|
164
200
|
### Create Atlassian Forge SQL Migration
|
|
165
201
|
|
|
166
202
|
```bash
|
|
167
|
-
|
|
203
|
+
npm run migration:create
|
|
168
204
|
```
|
|
169
205
|
|
|
170
|
-
This will create a new Atlassian Forge SQL migration file with SQL statements to update your database schema.
|
|
206
|
+
This will create a new Atlassian Forge SQL migration file with SQL statements to update your database schema. The `--force` flag allows overwriting existing migrations.
|
|
171
207
|
|
|
172
208
|
### Update Atlassian Forge SQL Migration
|
|
173
209
|
|
|
174
210
|
```bash
|
|
175
|
-
|
|
211
|
+
npm run migration:update
|
|
176
212
|
```
|
|
177
213
|
|
|
178
214
|
This will update an existing migration with the latest schema changes for Atlassian Forge SQL.
|
|
@@ -180,7 +216,7 @@ This will update an existing migration with the latest schema changes for Atlass
|
|
|
180
216
|
### Drop Tables with Atlassian Forge SQL Migration
|
|
181
217
|
|
|
182
218
|
```bash
|
|
183
|
-
|
|
219
|
+
npm run migration:drop
|
|
184
220
|
```
|
|
185
221
|
|
|
186
222
|
This will create a migration to drop specified tables from your Atlassian Forge SQL database.
|
package/dist-cli/cli.js
CHANGED
|
@@ -41,6 +41,11 @@ const generateModels = async (options) => {
|
|
|
41
41
|
const snapshotData = JSON.parse(fs.readFileSync(snapshotFile, "utf-8"));
|
|
42
42
|
for (const [tableName, tableData] of Object.entries(snapshotData.tables)) {
|
|
43
43
|
const table = tableData;
|
|
44
|
+
if (tableName.toLowerCase().startsWith("a_")) {
|
|
45
|
+
console.warn(
|
|
46
|
+
`⚠️ Table "${tableName}" starts with "a_". KVS Cache will not work with this table because such tables are ignored in cache operations.`
|
|
47
|
+
);
|
|
48
|
+
}
|
|
44
49
|
const versionField = Object.entries(table.columns).find(
|
|
45
50
|
([_, col]) => col.name.toLowerCase() === options.versionField
|
|
46
51
|
);
|
package/dist-cli/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","sources":["../src/actions/generate-models.ts","../src/actions/migrations-create.ts","../src/actions/migrations-update.ts","../src/actions/migrations-drops.ts","../src/cli.ts"],"sourcesContent":["import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { execSync } from \"child_process\";\n\n/**\n * Options for model generation\n */\ninterface GenerateModelsOptions {\n host: string;\n port: number;\n user: string;\n password: string;\n dbName: string;\n output: string;\n versionField: string;\n}\n\n/**\n * Interface for column metadata\n */\ninterface ColumnMetadata {\n autoincrement: boolean;\n name: string;\n type: string;\n primaryKey: boolean;\n notNull: boolean;\n}\n\n/**\n * Interface for table metadata\n */\ninterface TableMetadata {\n name: string;\n columns: Record<string, ColumnMetadata>;\n compositePrimaryKeys: Record<string, { name: string; columns: string[] }>;\n indexes: Record<string, any>;\n foreignKeys: Record<string, any>;\n uniqueConstraints: Record<string, any>;\n checkConstraint: Record<string, any>;\n}\n\n/**\n * Interface for version field metadata\n */\ninterface VersionFieldMetadata {\n fieldName: string;\n}\n\n/**\n * Interface for table version metadata\n */\ninterface TableVersionMetadata {\n tableName: string;\n versionField: VersionFieldMetadata;\n}\n\n/**\n * Type for additional metadata map\n */\ntype AdditionalMetadata = Record<string, TableVersionMetadata>;\n\n/**\n * Interface for journal entry\n */\ninterface JournalEntry {\n idx: number;\n version: string;\n when: number;\n tag: string;\n breakpoints: boolean;\n}\n\n/**\n * Interface for journal data\n */\ninterface JournalData {\n version: string;\n dialect: string;\n entries: JournalEntry[];\n}\n\n/**\n * Replaces MySQL types with custom types in the generated schema\n * @param schemaContent - The content of the generated schema file\n * @returns Modified schema content with custom types\n */\nfunction replaceMySQLTypes(schemaContent: string): string {\n // Add imports at the top of the file\n const imports = `import { forgeDateTimeString, forgeTimeString, forgeDateString, forgeTimestampString } from \"forge-sql-orm\";\\n\\n`;\n\n // Replace types in the content\n let modifiedContent = schemaContent\n // Handle datetime with column name and mode option\n .replace(\n /datetime\\(['\"]([^'\"]+)['\"],\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\)/g,\n \"forgeDateTimeString('$1')\",\n )\n // Handle datetime with column name only\n .replace(/datetime\\(['\"]([^'\"]+)['\"]\\)/g, \"forgeDateTimeString('$1')\")\n // Handle datetime with mode option only\n .replace(/datetime\\(\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\s*\\)/g, \"forgeDateTimeString()\")\n // Handle time with column name and mode option\n .replace(/time\\(['\"]([^'\"]+)['\"],\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\)/g, \"forgeTimeString('$1')\")\n // Handle time with column name only\n .replace(/time\\(['\"]([^'\"]+)['\"]\\)/g, \"forgeTimeString('$1')\")\n // Handle time with mode option only\n .replace(/time\\(\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\s*\\)/g, \"forgeTimeString()\")\n // Handle date with column name and mode option\n .replace(/date\\(['\"]([^'\"]+)['\"],\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\)/g, \"forgeDateString('$1')\")\n // Handle date with column name only\n .replace(/date\\(['\"]([^'\"]+)['\"]\\)/g, \"forgeDateString('$1')\")\n // Handle date with mode option only\n .replace(/date\\(\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\s*\\)/g, \"forgeDateString()\")\n // Handle timestamp with column name and mode option\n .replace(\n /timestamp\\(['\"]([^'\"]+)['\"],\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\)/g,\n \"forgeTimestampString('$1')\",\n )\n // Handle timestamp with column name only\n .replace(/timestamp\\(['\"]([^'\"]+)['\"]\\)/g, \"forgeTimestampString('$1')\")\n // Handle timestamp with mode option only\n .replace(/timestamp\\(\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\s*\\)/g, \"forgeTimestampString()\");\n\n // Add imports if they don't exist\n if (!modifiedContent.includes(\"import { forgeDateTimeString\")) {\n modifiedContent = imports + modifiedContent;\n }\n\n return modifiedContent;\n}\n\n/**\n * Generates models for all tables in the database using drizzle-kit\n * @param options - Generation options\n */\nexport const generateModels = async (options: GenerateModelsOptions) => {\n try {\n // Generate models using drizzle-kit pull\n await execSync(\n `npx drizzle-kit pull --dialect mysql --url mysql://${options.user}:${options.password}@${options.host}:${options.port}/${options.dbName} --out ${options.output}`,\n { encoding: \"utf-8\" },\n );\n\n // Process metadata to create version map\n const metaDir = path.join(options.output, \"meta\");\n const additionalMetadata: AdditionalMetadata = {};\n\n if (fs.existsSync(metaDir)) {\n const snapshotFile = path.join(metaDir, \"0000_snapshot.json\");\n if (fs.existsSync(snapshotFile)) {\n const snapshotData = JSON.parse(fs.readFileSync(snapshotFile, \"utf-8\"));\n\n // Process each table from the snapshot\n for (const [tableName, tableData] of Object.entries(snapshotData.tables)) {\n const table = tableData as TableMetadata;\n\n // Find version field in columns\n const versionField = Object.entries(table.columns).find(\n ([_, col]) => col.name.toLowerCase() === options.versionField,\n );\n\n if (versionField) {\n const [_, col] = versionField;\n const fieldType = col.type;\n const isSupportedType =\n fieldType === \"datetime\" ||\n fieldType === \"timestamp\" ||\n fieldType === \"int\" ||\n fieldType === \"number\" ||\n fieldType === \"decimal\";\n if (!col.notNull) {\n console.warn(\n `Version field \"${col.name}\" in table ${tableName} is nullable. Versioning may not work correctly.`,\n );\n } else if (!isSupportedType) {\n console.warn(\n `Version field \"${col.name}\" in table ${tableName} has unsupported type \"${fieldType}\". ` +\n `Only datetime, timestamp, int, and decimal types are supported for versioning. Versioning will be skipped.`,\n );\n } else {\n additionalMetadata[tableName] = {\n tableName,\n versionField: {\n fieldName: col.name,\n },\n };\n }\n }\n }\n }\n }\n\n // Create version metadata file\n const versionMetadataContent = `/**\n * This file was auto-generated by forge-sql-orm\n * Generated at: ${new Date().toISOString()}\n * \n * DO NOT EDIT THIS FILE MANUALLY\n * Any changes will be overwritten on next generation\n */\n \n \nexport * from \"./relations\";\nexport * from \"./schema\";\n\nexport interface VersionFieldMetadata {\n fieldName: string;\n}\n\nexport interface TableMetadata {\n tableName: string;\n versionField: VersionFieldMetadata;\n}\n\nexport type AdditionalMetadata = Record<string, TableMetadata>;\n\nexport const additionalMetadata: AdditionalMetadata = ${JSON.stringify(additionalMetadata, null, 2)};\n`;\n\n fs.writeFileSync(path.join(options.output, \"index.ts\"), versionMetadataContent);\n\n // Replace MySQL types in the generated schema file\n const schemaPath = path.join(options.output, \"schema.ts\");\n if (fs.existsSync(schemaPath)) {\n const schemaContent = fs.readFileSync(schemaPath, \"utf-8\");\n const modifiedContent = replaceMySQLTypes(schemaContent);\n fs.writeFileSync(schemaPath, modifiedContent);\n console.log(`✅ Updated schema types in: ${schemaPath}`);\n }\n\n // Remove migration files and meta directory if they exist\n const migrationDir = path.join(options.output, \"migrations\");\n\n if (fs.existsSync(migrationDir)) {\n fs.rmSync(migrationDir, { recursive: true, force: true });\n console.log(`✅ Removed: ${migrationDir}`);\n }\n\n // Read journal and remove corresponding SQL file\n if (fs.existsSync(metaDir)) {\n const journalFile = path.join(metaDir, \"_journal.json\");\n if (fs.existsSync(journalFile)) {\n const journalData = JSON.parse(fs.readFileSync(journalFile, \"utf-8\")) as JournalData;\n\n // Remove SQL files for each entry\n for (const entry of journalData.entries) {\n const sqlFile = path.join(options.output, `${entry.tag}.sql`);\n if (fs.existsSync(sqlFile)) {\n fs.rmSync(sqlFile, { force: true });\n console.log(`✅ Removed SQL file: ${entry.tag}.sql`);\n }\n }\n }\n\n // Remove meta directory after processing\n fs.rmSync(metaDir, { recursive: true, force: true });\n console.log(`✅ Removed: ${metaDir}`);\n }\n\n console.log(`✅ Successfully generated models and version metadata`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error during model generation:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\n\nimport { execSync } from \"child_process\";\n\n/**\n * Options for migration creation\n */\nexport interface CreateMigrationOptions {\n output: string;\n entitiesPath: string;\n force?: boolean;\n}\n\n/**\n * Loads the current migration version from `migrationCount.ts`.\n * @param migrationPath - Path to the migration folder.\n * @returns The latest migration version.\n */\nexport const loadMigrationVersion = async (migrationPath: string): Promise<number> => {\n try {\n const migrationCountFilePath = path.resolve(path.join(migrationPath, \"migrationCount.ts\"));\n if (!fs.existsSync(migrationCountFilePath)) {\n console.log(`✅ Current migration version: 0`);\n return 0;\n }\n\n const { MIGRATION_VERSION } = await import(migrationCountFilePath);\n console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);\n return MIGRATION_VERSION as number;\n } catch (error) {\n console.error(`❌ Error loading migrationCount:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Cleans SQL statements by removing unnecessary database options.\n * @param sql - The raw SQL statement.\n * @returns The cleaned SQL statement.\n */\nexport function cleanSQLStatement(sql: string): string {\n // Add IF NOT EXISTS to CREATE TABLE statements\n sql = sql.replace(/create\\s+table\\s+(\\w+)/gi, \"create table if not exists $1\");\n\n // Add IF NOT EXISTS to CREATE INDEX statements\n sql = sql.replace(/create\\s+index\\s+(\\w+)/gi, \"create index if not exists $1\");\n\n // Add IF NOT EXISTS to ADD INDEX statements\n sql = sql.replace(\n /alter\\s+table\\s+(\\w+)\\s+add\\s+index\\s+(\\w+)/gi,\n \"alter table $1 add index if not exists $2\",\n );\n\n // Add IF NOT EXISTS to ADD CONSTRAINT statements\n sql = sql.replace(\n /alter\\s+table\\s+(\\w+)\\s+add\\s+constraint\\s+(\\w+)/gi,\n \"alter table $1 add constraint if not exists $2\",\n );\n\n // Remove unnecessary database options\n return sql.replace(/\\s+default\\s+character\\s+set\\s+utf8mb4\\s+engine\\s*=\\s*InnoDB;?/gi, \"\").trim();\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nexport function generateMigrationFile(createStatements: string[], version: number): string {\n const versionPrefix = `v${version}_MIGRATION`;\n\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map(\n (stmt, index) =>\n ` .enqueue(\"${versionPrefix}${index}\", \"${cleanSQLStatement(stmt).replace(/\\s+/g, \" \")}\")`,\n )\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n */\nexport function saveMigrationFiles(migrationCode: string, version: number, outputDir: string) {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file with static imports\n // Build import lines for each migration version\n const importLines = [];\n for (let i = 1; i <= version; i++) {\n importLines.push(`import v${i} from \"./migrationV${i}\";`);\n }\n // Build call lines for each migration version\n const callLines = [];\n for (let i = 1; i <= version; i++) {\n callLines.push(` v${i}(migrationRunner);`);\n }\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\n${importLines.join(\"\\n\")}\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n${callLines.join(\"\\n\")}\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n}\n\n/**\n * Extracts only the relevant SQL statements for migration.\n * @param schema - The full database schema as SQL.\n * @returns Filtered list of SQL statements.\n */\nexport const extractCreateStatements = (schema: string): string[] => {\n // Split by statement-breakpoint and semicolon\n const statements = schema\n .split(/--> statement-breakpoint|;/)\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n\n return statements.filter(\n (stmt) =>\n stmt.toLowerCase().startsWith(\"create table\") ||\n stmt.toLowerCase().startsWith(\"alter table\") ||\n stmt.toLowerCase().includes(\"add index\") ||\n stmt.toLowerCase().includes(\"create index\") ||\n stmt.toLowerCase().includes(\"add unique index\") ||\n stmt.toLowerCase().includes(\"add constraint\"),\n );\n};\n\n/**\n * Creates a full database migration.\n * @param options - Database connection settings and output paths.\n */\nexport const createMigration = async (options: CreateMigrationOptions) => {\n try {\n let version = await loadMigrationVersion(options.output);\n\n if (version > 0) {\n if (options.force) {\n console.warn(\n `⚠️ Warning: Migration already exists. Creating new migration with force flag...`,\n );\n } else {\n console.error(\n `❌ Error: Migration has already been created. Use --force flag to override.`,\n );\n process.exit(1);\n }\n }\n\n // Generate SQL using drizzle-kit\n await execSync(\n `npx drizzle-kit generate --name=init --dialect mysql --out ${options.output} --schema ${options.entitiesPath}`,\n { encoding: \"utf-8\" },\n );\n const initSqlFile = path.join(options.output, \"0000_init.sql\");\n const sql = fs.readFileSync(initSqlFile, \"utf-8\");\n\n // Extract and clean statements\n const createStatements = extractCreateStatements(sql);\n\n // Generate and save migration files\n const migrationFile = generateMigrationFile(createStatements, 1);\n saveMigrationFiles(migrationFile, 1, options.output);\n\n fs.rmSync(initSqlFile, { force: true });\n console.log(`✅ Removed SQL file: ${initSqlFile}`);\n // Remove meta directory after processing\n let metaDir = path.join(options.output, \"meta\");\n fs.rmSync(metaDir, { recursive: true, force: true });\n console.log(`✅ Removed: ${metaDir}`);\n console.log(`✅ Migration successfully created!`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error during migration creation:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport mysql from \"mysql2/promise\";\nimport { MySqlTable, TableConfig } from \"drizzle-orm/mysql-core\";\nimport { RowDataPacket } from \"mysql2\";\nimport { getTableMetadata } from \"forge-sql-orm\";\nimport { AnyIndexBuilder } from \"drizzle-orm/mysql-core/indexes\";\nimport { ForeignKeyBuilder } from \"drizzle-orm/mysql-core/foreign-keys\";\nimport { UniqueConstraintBuilder } from \"drizzle-orm/mysql-core/unique-constraint\";\n\ninterface DrizzleColumn {\n type: string;\n notNull: boolean;\n autoincrement?: boolean;\n columnType?: any;\n name: string;\n getSQLType: () => string;\n}\n\ninterface DrizzleSchema {\n [tableName: string]: {\n [columnName: string]: DrizzleColumn;\n };\n}\n\ninterface DatabaseColumn extends RowDataPacket {\n TABLE_NAME: string;\n COLUMN_NAME: string;\n COLUMN_TYPE: string;\n IS_NULLABLE: string;\n COLUMN_KEY: string;\n EXTRA: string;\n}\n\ninterface DatabaseIndex extends RowDataPacket {\n TABLE_NAME: string;\n INDEX_NAME: string;\n COLUMN_NAME: string;\n NON_UNIQUE: number;\n}\n\ninterface DatabaseForeignKey extends RowDataPacket {\n TABLE_NAME: string;\n COLUMN_NAME: string;\n CONSTRAINT_NAME: string;\n REFERENCED_TABLE_NAME: string;\n REFERENCED_COLUMN_NAME: string;\n}\n\ninterface TableSchema {\n columns: Record<string, DatabaseColumn>;\n indexes: Record<\n string,\n {\n columns: string[];\n unique: boolean;\n }\n >;\n foreignKeys: Record<\n string,\n {\n column: string;\n referencedTable: string;\n referencedColumn: string;\n }\n >;\n}\n\ninterface DatabaseSchema {\n [tableName: string]: TableSchema;\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nfunction generateMigrationFile(createStatements: string[], version: number): string {\n const versionPrefix = `v${version}_MIGRATION`;\n\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map((stmt, index) => ` .enqueue(\"${versionPrefix}${index}\", \"${stmt}\")`)\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Filters out SQL statements that already exist in the previous migration file\n * @param newStatements - Array of SQL statements from new migration\n * @param prevVersion - Previous migration version\n * @param outputDir - Directory where migration files are stored\n * @returns Array of SQL statements that don't exist in previous migration\n */\nfunction filterWithPreviousMigration(\n newStatements: string[],\n prevVersion: number,\n outputDir: string,\n): string[] {\n const prevMigrationPath = path.join(outputDir, `migrationV${prevVersion}.ts`);\n\n if (!fs.existsSync(prevMigrationPath)) {\n return newStatements.map((s) => s.replace(/\\s+/g, \" \"));\n }\n\n // Read previous migration file\n const prevContent = fs.readFileSync(prevMigrationPath, \"utf-8\");\n\n // Extract SQL statements from the file\n const prevStatements = prevContent\n .split(\"\\n\")\n .filter((line) => line.includes(\".enqueue(\"))\n .map((line) => {\n const match = line.match(/\\.enqueue\\([^,]+,\\s*\"([^\"]+)\"/);\n return match ? match[1].replace(/\\s+/g, \" \").trim() : \"\";\n });\n\n // Filter out statements that already exist in previous migration\n return newStatements\n .filter((s) => !prevStatements.includes(s.replace(/\\s+/g, \" \")))\n .map((s) => s.replace(/\\s+/g, \" \"));\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n * @returns boolean indicating if migration was saved\n */\nfunction saveMigrationFiles(migrationCode: string, version: number, outputDir: string): boolean {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\nimport { MIGRATION_VERSION } from \"./migrationCount\";\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n for (let i = 1; i <= MIGRATION_VERSION; i++) {\n const migrations = (await import(\\`./migrationV\\${i}\\`)) as {\n default: MigrationType;\n };\n migrations.default(migrationRunner);\n }\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n\n return true;\n}\n\n/**\n * Loads the current migration version from `migrationCount.ts`.\n * @param migrationPath - Path to the migration folder.\n * @returns The latest migration version.\n */\nconst loadMigrationVersion = async (migrationPath: string): Promise<number> => {\n try {\n const migrationCountFilePath = path.resolve(path.join(migrationPath, \"migrationCount.ts\"));\n if (!fs.existsSync(migrationCountFilePath)) {\n console.warn(\n `⚠️ Warning: migrationCount.ts not found in ${migrationCountFilePath}, assuming no previous migrations.`,\n );\n return 0;\n }\n\n const { MIGRATION_VERSION } = await import(migrationCountFilePath);\n console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);\n return MIGRATION_VERSION as number;\n } catch (error) {\n console.error(`❌ Error loading migrationCount:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Gets the current database schema from MySQL including indexes and foreign keys\n * @param connection - MySQL connection\n * @param dbName - Database name\n * @returns Database schema object with indexes and foreign keys\n */\nasync function getDatabaseSchema(\n connection: mysql.Connection,\n dbName: string,\n): Promise<DatabaseSchema> {\n // Get columns\n const [columns] = await connection.execute<DatabaseColumn[]>(\n `\n SELECT TABLE_NAME, COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY, EXTRA\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_SCHEMA = ?\n `,\n [dbName],\n );\n\n // Get indexes\n const [indexes] = await connection.execute<DatabaseIndex[]>(\n `\n SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, NON_UNIQUE\n FROM INFORMATION_SCHEMA.STATISTICS\n WHERE TABLE_SCHEMA = ?\n ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX\n `,\n [dbName],\n );\n\n // Get foreign keys\n const [foreignKeys] = await connection.execute<DatabaseForeignKey[]>(\n `\n SELECT \n TABLE_NAME,\n COLUMN_NAME,\n CONSTRAINT_NAME,\n REFERENCED_TABLE_NAME,\n REFERENCED_COLUMN_NAME\n FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE\n WHERE TABLE_SCHEMA = ?\n AND REFERENCED_TABLE_NAME IS NOT NULL\n `,\n [dbName],\n );\n\n const schema: DatabaseSchema = {};\n\n // Process columns\n columns.forEach((row) => {\n if (!schema[row.TABLE_NAME]) {\n schema[row.TABLE_NAME] = {\n columns: {},\n indexes: {},\n foreignKeys: {},\n };\n }\n schema[row.TABLE_NAME].columns[row.COLUMN_NAME] = row;\n });\n\n // Process indexes\n indexes.forEach((row) => {\n if (!schema[row.TABLE_NAME].indexes[row.INDEX_NAME]) {\n schema[row.TABLE_NAME].indexes[row.INDEX_NAME] = {\n columns: [],\n unique: !row.NON_UNIQUE,\n };\n }\n schema[row.TABLE_NAME].indexes[row.INDEX_NAME].columns.push(row.COLUMN_NAME);\n });\n\n // Process foreign keys\n foreignKeys.forEach((row) => {\n if (!schema[row.TABLE_NAME].foreignKeys[row.CONSTRAINT_NAME]) {\n schema[row.TABLE_NAME].foreignKeys[row.CONSTRAINT_NAME] = {\n column: row.COLUMN_NAME,\n referencedTable: row.REFERENCED_TABLE_NAME,\n referencedColumn: row.REFERENCED_COLUMN_NAME,\n };\n }\n });\n\n return schema;\n}\n\n/**\n * Converts MySQL type to normalized format for comparison\n * @param mysqlType - MySQL type from INFORMATION_SCHEMA or Drizzle type\n * @returns Normalized type string\n */\nfunction normalizeMySQLType(mysqlType: string): string {\n // Remove length/precision information\n let normalized = mysqlType.replace(/\\([^)]*\\)/, \"\").toLowerCase();\n\n // Remove 'mysql' prefix from Drizzle types\n normalized = normalized.replace(/^mysql/, \"\");\n\n return normalized;\n}\n\n/**\n * Gets the name of a foreign key constraint\n * @param fk - The foreign key builder\n * @returns The name of the foreign key constraint\n */\nfunction getForeignKeyName(fk: ForeignKeyBuilder): string {\n // @ts-ignore - Internal property access\n return fk.name;\n}\n\n/**\n * Gets the name of an index\n * @param index - The index builder\n * @returns The name of the index\n */\nfunction getIndexName(index: AnyIndexBuilder): string {\n // @ts-ignore - Internal property access\n return index.name;\n}\n\n/**\n * Gets the name of a unique constraint\n * @param uc - The unique constraint builder\n * @returns The name of the unique constraint\n */\nfunction getUniqueConstraintName(uc: UniqueConstraintBuilder): string {\n // @ts-ignore - Internal property access\n return uc.name;\n}\n\n/**\n * Gets the columns of an index\n * @param index - The index builder\n * @returns Array of column names\n */\nfunction getIndexColumns(index: AnyIndexBuilder): string[] {\n // @ts-ignore - Internal property access\n return index.columns.map((col) => col.name);\n}\n\nfunction compareForeignKey(\n fk: ForeignKeyBuilder,\n { columns }: { columns: string[]; unique: boolean },\n) {\n // @ts-ignore\n const fcolumns: string[] = fk.columns.map((c) => c.name);\n return fcolumns.sort().join(\",\") === columns.sort().join(\",\");\n}\n\n/**\n * Generates SQL changes by comparing Drizzle schema with database schema\n * @param drizzleSchema - Schema from Drizzle\n * @param dbSchema - Schema from database\n * @param schemaModule - Drizzle schema module\n * @returns Array of SQL statements\n */\nfunction generateSchemaChanges(\n drizzleSchema: DrizzleSchema,\n dbSchema: DatabaseSchema,\n schemaModule: Record<string, any>,\n): string[] {\n const changes: string[] = [];\n\n // First check existing tables in database\n for (const [tableName, dbTable] of Object.entries(dbSchema)) {\n const drizzleColumns = drizzleSchema[tableName];\n\n if (!drizzleColumns) {\n // Table exists in database but not in schema - create it\n const columns = Object.entries(dbTable.columns)\n .map(([colName, col]) => {\n const type = col.COLUMN_TYPE;\n const nullable = col.IS_NULLABLE === \"YES\" ? \"NULL\" : \"NOT NULL\";\n const autoIncrement = col.EXTRA.includes(\"auto_increment\") ? \"AUTO_INCREMENT\" : \"\";\n return `\\`${colName}\\` ${type} ${nullable} ${autoIncrement}`.trim();\n })\n .join(\",\\n \");\n\n changes.push(`CREATE TABLE if not exists \\`${tableName}\\` (\\n ${columns}\\n);`);\n\n // Create indexes for new table\n for (const [indexName, dbIndex] of Object.entries(dbTable.indexes)) {\n // Skip primary key and foreign key indexes\n if (indexName === \"PRIMARY\") {\n continue;\n }\n\n // Check if any column in this index is a foreign key\n const isForeignKeyIndex = dbIndex.columns.some((colName) => {\n const column = dbTable.columns[colName];\n return column && column.COLUMN_KEY === \"MUL\" && column.EXTRA.includes(\"foreign key\");\n });\n\n if (isForeignKeyIndex) {\n continue;\n }\n\n // Create index\n const columns = dbIndex.columns.map((col) => `\\`${col}\\``).join(\", \");\n const unique = dbIndex.unique ? \"UNIQUE \" : \"\";\n changes.push(\n `CREATE ${unique}INDEX if not exists \\`${indexName}\\` ON \\`${tableName}\\` (${columns});`,\n );\n }\n\n // Create foreign keys for new table\n for (const [fkName, dbFK] of Object.entries(dbTable.foreignKeys)) {\n changes.push(\n `ALTER TABLE \\`${tableName}\\` ADD CONSTRAINT \\`${fkName}\\` FOREIGN KEY (\\`${dbFK.column}\\`) REFERENCES \\`${dbFK.referencedTable}\\` (\\`${dbFK.referencedColumn}\\`);`,\n );\n }\n continue;\n }\n\n // Check for column changes in existing tables\n for (const [colName, dbCol] of Object.entries(dbTable.columns)) {\n const drizzleCol = Object.values(drizzleColumns).find((c) => c.name === colName);\n\n if (!drizzleCol) {\n // Column exists in database but not in schema - create it\n const type = dbCol.COLUMN_TYPE;\n const nullable = dbCol.IS_NULLABLE === \"YES\" ? \"NULL\" : \"NOT NULL\";\n changes.push(`ALTER TABLE \\`${tableName}\\` ADD COLUMN IF NOT EXISTS \\`${colName}\\` ${type} ${nullable};`);\n continue;\n }\n\n // Check for type changes\n const normalizedDbType = normalizeMySQLType(dbCol.COLUMN_TYPE);\n const normalizedDrizzleType = normalizeMySQLType(drizzleCol.getSQLType());\n\n if (normalizedDbType !== normalizedDrizzleType) {\n const type = dbCol.COLUMN_TYPE; // Use database type as source of truth\n const nullable = dbCol.IS_NULLABLE === \"YES\" ? \"NULL\" : \"NOT NULL\";\n changes.push(\n `ALTER TABLE \\`${tableName}\\` MODIFY COLUMN \\`${colName}\\` IF EXISTS ${type} ${nullable};`,\n );\n }\n }\n\n // Check for index changes\n const table = Object.values(schemaModule).find((t) => {\n const metadata = getTableMetadata(t);\n return metadata.tableName === tableName;\n });\n\n if (table) {\n const metadata = getTableMetadata(table);\n // First check indexes that exist in database but not in schema\n for (const [indexName, dbIndex] of Object.entries(dbTable.indexes)) {\n // Skip primary key and foreign key indexes\n if (indexName === \"PRIMARY\") {\n continue;\n }\n\n // Check if this is a foreign key index\n const isForeignKeyIndex = metadata.foreignKeys.some(\n (fk) => getForeignKeyName(fk) === indexName || compareForeignKey(fk, dbIndex),\n );\n if (isForeignKeyIndex) {\n continue;\n }\n\n // Check if this is a unique constraint\n const existsUniqIndex = metadata.uniqueConstraints.find(\n (uc) => getUniqueConstraintName(uc) === indexName,\n );\n let drizzleIndex = metadata.indexes.find((i) => getIndexName(i) === indexName);\n\n if (!drizzleIndex && existsUniqIndex) {\n drizzleIndex = existsUniqIndex as unknown as AnyIndexBuilder;\n }\n\n if (!drizzleIndex) {\n // Index exists in database but not in schema - create it\n const columns = dbIndex.columns.map((col) => `\\`${col}\\``).join(\", \");\n const unique = dbIndex.unique ? \"UNIQUE \" : \"\";\n changes.push(\n `CREATE ${unique}INDEX if not exists \\`${indexName}\\` ON \\`${tableName}\\` (${columns});`,\n );\n continue;\n }\n\n // Check if index columns changed\n const dbColumns = dbIndex.columns.join(\", \");\n const drizzleColumns = getIndexColumns(drizzleIndex).join(\", \");\n if (\n dbColumns !== drizzleColumns ||\n dbIndex.unique !== drizzleIndex instanceof UniqueConstraintBuilder\n ) {\n // Drop and recreate index using database values\n changes.push(`DROP INDEX \\`${indexName}\\` ON \\`${tableName}\\`;`);\n const columns = dbIndex.columns.map((col) => `\\`${col}\\``).join(\", \");\n const unique = dbIndex.unique ? \"UNIQUE \" : \"\";\n changes.push(\n `CREATE ${unique}INDEX if not exists \\`${indexName}\\` ON \\`${tableName}\\` (${columns});`,\n );\n }\n }\n\n // First check foreign keys that exist in database but not in schema\n for (const [fkName, dbFK] of Object.entries(dbTable.foreignKeys)) {\n // Find if this column is referenced in Drizzle schema\n const drizzleFK = metadata.foreignKeys.find(\n (fk) =>\n getForeignKeyName(fk) === fkName ||\n compareForeignKey(fk, { columns: [dbFK.column], unique: false }),\n );\n\n if (!drizzleFK) {\n // Foreign key exists in database but not in schema - drop it\n changes.push(\n `ALTER TABLE \\`${tableName}\\` ADD CONSTRAINT \\`${fkName}\\` FOREIGN KEY (\\`${dbFK.column}\\`) REFERENCES \\`${dbFK.referencedTable}\\` (\\`${dbFK.referencedColumn}\\`);`,\n );\n continue;\n }\n }\n\n // Then check for new foreign keys that exist in schema but not in database\n for (const drizzleForeignKey of metadata.foreignKeys) {\n // Find if this foreign key exists in database\n const isDbFk = Object.keys(dbTable.foreignKeys).find((fk) => {\n let foreignKey = dbTable.foreignKeys[fk];\n return (\n fk === getForeignKeyName(drizzleForeignKey) ||\n compareForeignKey(drizzleForeignKey, { columns: [foreignKey.column], unique: false })\n );\n });\n\n if (!isDbFk) {\n // Foreign key exists in schema but not in database - create it\n if (drizzleForeignKey) {\n const fkName = getForeignKeyName(drizzleForeignKey);\n if (fkName) {\n changes.push(`ALTER TABLE \\`${tableName}\\` DROP FOREIGN KEY \\`${fkName}\\`;`);\n } else {\n // @ts-ignore\n const columns = drizzleForeignKey.columns;\n const columnNames = columns?.length\n ? columns.map((c: any) => c.name).join(\", \")\n : \"unknown columns\";\n console.warn(\n `⚠️ Drizzle model for table '${tableName}' does not provide a name for FOREIGN KEY constraint on columns: ${columnNames}`,\n );\n }\n }\n }\n }\n }\n }\n\n return changes;\n}\n\n/**\n * Updates an existing database migration by generating schema modifications.\n * @param options - Database connection settings and output paths.\n */\nexport const updateMigration = async (options: any) => {\n try {\n let version = await loadMigrationVersion(options.output);\n const prevVersion = version;\n\n if (version < 1) {\n console.log(\n `⚠️ Initial migration not found. Run \"npx forge-sql-orm migrations:create\" first.`,\n );\n process.exit(0);\n }\n version += 1;\n\n // Create database connection\n const connection = await mysql.createConnection({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n database: options.dbName,\n });\n\n try {\n // Get current database schema\n const dbSchema = await getDatabaseSchema(connection, options.dbName);\n\n // Import Drizzle schema using absolute path\n const schemaPath = path.resolve(options.entitiesPath, \"schema.ts\");\n if (!fs.existsSync(schemaPath)) {\n throw new Error(`Schema file not found at: ${schemaPath}`);\n }\n\n const schemaModule = await import(schemaPath);\n if (!schemaModule) {\n throw new Error(`Invalid schema file at: ${schemaPath}. Schema must export tables.`);\n }\n\n // Process exported tables\n const drizzleSchema: DrizzleSchema = {};\n\n // Get all exports that are tables\n const tables = Object.values(schemaModule) as MySqlTable<TableConfig>[];\n\n tables.forEach((table) => {\n const metadata = getTableMetadata(table);\n if (metadata.tableName) {\n // Convert AnyColumn to DrizzleColumn\n const columns: Record<string, DrizzleColumn> = {};\n Object.entries(metadata.columns).forEach(([name, column]) => {\n columns[name] = {\n type: column.dataType,\n notNull: column.notNull,\n autoincrement: (column as any).autoincrement,\n columnType: column.columnType,\n name: column.name,\n getSQLType: () => column.getSQLType(),\n };\n });\n drizzleSchema[metadata.tableName] = columns;\n }\n });\n\n if (Object.keys(drizzleSchema).length === 0) {\n throw new Error(`No valid tables found in schema at: ${schemaPath}`);\n }\n\n console.log(\"Found tables:\", Object.keys(drizzleSchema));\n\n // Generate SQL changes\n const createStatements = filterWithPreviousMigration(\n generateSchemaChanges(drizzleSchema, dbSchema, schemaModule),\n prevVersion,\n options.output,\n );\n\n if (createStatements.length) {\n // Generate migration file content\n const migrationFile = generateMigrationFile(createStatements, version);\n\n // Save migration files only if there are actual changes\n if (saveMigrationFiles(migrationFile, version, options.output)) {\n console.log(`✅ Migration successfully updated!`);\n }\n process.exit(0);\n } else {\n console.log(`⚠️ No new migration changes detected.`);\n process.exit(0);\n }\n } finally {\n await connection.end();\n }\n } catch (error) {\n console.error(`❌ Error during migration update:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { MySqlTable, TableConfig } from \"drizzle-orm/mysql-core\";\nimport { getTableMetadata, generateDropTableStatements } from \"forge-sql-orm\";\n\n/**\n * Generates a migration ID using current date\n * @returns Migration ID string with current date\n */\nfunction generateMigrationUUID(version: number): string {\n const now = new Date();\n const timestamp = now.getTime();\n return `MIGRATION_V${version}_${timestamp}`;\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nfunction generateMigrationFile(createStatements: string[], version: number): string {\n const uniqId = generateMigrationUUID(version);\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map(\n (stmt, index) => ` .enqueue(\"${uniqId}_${index}\", \\\"${stmt}\\\")`, // eslint-disable-line no-useless-escape\n )\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n */\nfunction saveMigrationFiles(migrationCode: string, version: number, outputDir: string) {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\nimport { MIGRATION_VERSION } from \"./migrationCount\";\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n for (let i = 1; i <= MIGRATION_VERSION; i++) {\n const migrations = (await import(\\`./migrationV\\${i}\\`)) as {\n default: MigrationType;\n };\n migrations.default(migrationRunner);\n }\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n}\n\n/**\n * Creates a full database migration.\n * @param options - Database connection settings and output paths.\n */\nexport const dropMigration = async (options: any) => {\n try {\n // Start from version 1 if no previous migrations exist\n const version = 1;\n\n // Import Drizzle schema using absolute path\n const schemaPath = path.resolve(options.entitiesPath, \"schema.ts\");\n if (!fs.existsSync(schemaPath)) {\n throw new Error(`Schema file not found at: ${schemaPath}`);\n }\n\n const schemaModule = await import(schemaPath);\n if (!schemaModule) {\n throw new Error(`Invalid schema file at: ${schemaPath}. Schema must export tables.`);\n }\n\n // Get all exports that are tables\n const tables = Object.values(schemaModule) as MySqlTable<TableConfig>[];\n\n if (tables.length === 0) {\n throw new Error(`No valid tables found in schema at: ${schemaPath}`);\n }\n\n // Get table names for logging\n const tableNames = tables\n .map((table) => {\n const metadata = getTableMetadata(table);\n return metadata.tableName;\n })\n .filter(Boolean);\n\n console.log(\"Found tables:\", tableNames);\n\n // Generate drop statements\n const dropStatements = generateDropTableStatements(tableNames);\n\n // Generate and save migration files\n const migrationFile = generateMigrationFile(dropStatements, version);\n saveMigrationFiles(migrationFile, version, options.output);\n\n console.log(`✅ Migration successfully created!`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error during migration creation:`, error);\n process.exit(1);\n }\n};\n","#!/usr/bin/env node\n\nimport { Command } from \"commander\";\nimport dotenv from \"dotenv\";\nimport inquirer from \"inquirer\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { generateModels } from \"./actions/generate-models\";\nimport { createMigration } from \"./actions/migrations-create\";\nimport { updateMigration } from \"./actions/migrations-update\";\nimport { dropMigration } from \"./actions/migrations-drops\";\n\nconst ENV_PATH = path.resolve(process.cwd(), \".env\");\n// 🔄 Load environment variables from `.env` file\ndotenv.config({ path: ENV_PATH });\n\nconst saveEnvFile = (config: any) => {\n let envContent = \"\";\n const envFilePath = ENV_PATH;\n\n if (fs.existsSync(envFilePath)) {\n envContent = fs.readFileSync(envFilePath, \"utf8\");\n }\n\n const envVars = envContent\n .split(\"\\n\")\n .filter((line) => line.trim() !== \"\" && !line.startsWith(\"#\"))\n .reduce((acc: any, line) => {\n const [key, ...value] = line.split(\"=\");\n acc[key] = value.join(\"=\");\n return acc;\n }, {});\n\n Object.entries(config).forEach(([key, value]) => {\n envVars[`FORGE_SQL_ORM_${key.toUpperCase()}`] = value;\n });\n\n const updatedEnvContent = Object.entries(envVars)\n .map(([key, value]) => `${key}=${value}`)\n .join(\"\\n\");\n\n fs.writeFileSync(envFilePath, updatedEnvContent, { encoding: \"utf8\" });\n\n console.log(\"✅ Configuration saved to .env without overwriting other variables.\");\n};\n\n/**\n * Prompts the user for missing parameters using Inquirer.js.\n * @param config - The current configuration object.\n * @param defaultOutput - Default output path.\n * @param customAskMissingParams - Optional function for additional prompts.\n * @returns Updated configuration with user input.\n */\nconst askMissingParams = async (\n config: any,\n defaultOutput: string,\n customAskMissingParams?: (cfg: any, questions: unknown[]) => void,\n) => {\n const questions: unknown[] = [];\n\n if (!config.host)\n questions.push({\n type: \"input\",\n name: \"host\",\n message: \"Enter database host:\",\n default: \"localhost\",\n });\n\n if (!config.port)\n questions.push({\n type: \"input\",\n name: \"port\",\n message: \"Enter database port:\",\n default: \"3306\",\n validate: (input: string) => !isNaN(parseInt(input, 10)),\n });\n\n if (!config.user)\n questions.push({\n type: \"input\",\n name: \"user\",\n message: \"Enter database user:\",\n default: \"root\",\n });\n\n if (!config.password)\n questions.push({\n type: \"password\",\n name: \"password\",\n message: \"Enter database password:\",\n mask: \"*\",\n });\n\n if (!config.dbName)\n questions.push({\n type: \"input\",\n name: \"dbName\",\n message: \"Enter database name:\",\n });\n\n if (!config.output)\n questions.push({\n type: \"input\",\n name: \"output\",\n message: \"Enter output path:\",\n default: defaultOutput,\n });\n\n // Allow additional questions from the caller\n if (customAskMissingParams) {\n customAskMissingParams(config, questions);\n }\n\n // If there are missing parameters, prompt the user\n if (questions.length > 0) {\n // @ts-ignore - Ignore TypeScript warning for dynamic question type\n const answers = await inquirer.prompt(questions);\n return { ...config, ...answers, port: parseInt(config.port ?? answers.port, 10) };\n }\n\n return config;\n};\n\n/**\n * Retrieves configuration parameters from command-line arguments and environment variables.\n * If any required parameters are missing, prompts the user for input.\n * @param cmd - The command object containing CLI options.\n * @param defaultOutput - Default output directory.\n * @param customConfig - Optional function for additional configuration parameters.\n * @param customAskMissingParams - Optional function for additional prompts.\n * @returns A fully resolved configuration object.\n */\nconst getConfig = async (\n cmd: any,\n defaultOutput: string,\n customConfig?: () => any,\n customAskMissingParams?: (cfg: any, questions: unknown[]) => void,\n) => {\n let config = {\n host: cmd.host || process.env.FORGE_SQL_ORM_HOST,\n port: cmd.port\n ? parseInt(cmd.port, 10)\n : process.env.FORGE_SQL_ORM_PORT\n ? parseInt(process.env.FORGE_SQL_ORM_PORT, 10)\n : undefined,\n user: cmd.user || process.env.FORGE_SQL_ORM_USER,\n password: cmd.password || process.env.FORGE_SQL_ORM_PASSWORD,\n dbName: cmd.dbName || process.env.FORGE_SQL_ORM_DBNAME,\n output: cmd.output || process.env.FORGE_SQL_ORM_OUTPUT,\n };\n\n // Merge additional configurations if provided\n if (customConfig) {\n config = { ...config, ...customConfig() };\n }\n\n const conf = await askMissingParams(config, defaultOutput, customAskMissingParams);\n if (cmd.saveEnv) {\n saveEnvFile(conf);\n }\n return conf;\n};\n\n// 📌 Initialize CLI\nexport const program = new Command();\nprogram.version(\"1.0.0\");\n\n// ✅ Command: Generate database models (Entities)\nprogram\n .command(\"generate:model\")\n .description(\"Generate Drizzle models from the database.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for entities\")\n .option(\"--versionField <string>\", \"Field name for versioning\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/entities\",\n () => ({\n versionField: cmd.versionField || process.env.FORGE_SQL_ORM_VERSIONFIELD,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.versionField) {\n questions.push({\n type: \"input\",\n name: \"versionField\",\n message: \"Enter the field name for versioning (leave empty to skip):\",\n default: \"\",\n });\n }\n },\n );\n await generateModels(config);\n });\n\n// ✅ Command: Create initial database migration\nprogram\n .command(\"migrations:create\")\n .description(\"Generate an initial migration for the entire database.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--force\", \"Force creation even if migrations exist\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n force: cmd.force || false,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await createMigration(config);\n });\n\n// ✅ Command: Update migration for schema changes\nprogram\n .command(\"migrations:update\")\n .description(\"Generate a migration to update the database schema.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await updateMigration(config);\n });\n\n// ✅ Command: Drop all migrations\nprogram\n .command(\"migrations:drop\")\n .description(\"Generate a migration to drop all tables and clear migrations history.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await dropMigration(config);\n });\n\n// 🔥 Execute CLI\n program.parse(process.argv);\n"],"names":["execSync","loadMigrationVersion","generateMigrationFile","saveMigrationFiles","columns","getTableMetadata","drizzleColumns","UniqueConstraintBuilder","generateDropTableStatements","Command"],"mappings":";;;;;;;;;;;;;AAuFA,SAAS,kBAAkB,eAA+B;AAExD,QAAM,UAAU;AAAA;AAAA;AAGhB,MAAI,kBAAkB,cAEnB;AAAA,IACC;AAAA,IACA;AAAA,EAAA,EAGD,QAAQ,iCAAiC,2BAA2B,EAEpE,QAAQ,qDAAqD,uBAAuB,EAEpF,QAAQ,+DAA+D,uBAAuB,EAE9F,QAAQ,6BAA6B,uBAAuB,EAE5D,QAAQ,iDAAiD,mBAAmB,EAE5E,QAAQ,+DAA+D,uBAAuB,EAE9F,QAAQ,6BAA6B,uBAAuB,EAE5D,QAAQ,iDAAiD,mBAAmB,EAE5E;AAAA,IACC;AAAA,IACA;AAAA,EAAA,EAGD,QAAQ,kCAAkC,4BAA4B,EAEtE,QAAQ,sDAAsD,wBAAwB;AAGzF,MAAI,CAAC,gBAAgB,SAAS,8BAA8B,GAAG;AAC7D,sBAAkB,UAAU;AAAA,EAC9B;AAEA,SAAO;AACT;AAMO,MAAM,iBAAiB,OAAO,YAAmC;AACtE,MAAI;AAEF,UAAMA,cAAAA;AAAAA,MACJ,sDAAsD,QAAQ,IAAI,IAAI,QAAQ,QAAQ,IAAI,QAAQ,IAAI,IAAI,QAAQ,IAAI,IAAI,QAAQ,MAAM,UAAU,QAAQ,MAAM;AAAA,MAChK,EAAE,UAAU,QAAA;AAAA,IAAQ;AAItB,UAAM,UAAU,KAAK,KAAK,QAAQ,QAAQ,MAAM;AAChD,UAAM,qBAAyC,CAAA;AAE/C,QAAI,GAAG,WAAW,OAAO,GAAG;AAC1B,YAAM,eAAe,KAAK,KAAK,SAAS,oBAAoB;AAC5D,UAAI,GAAG,WAAW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
+
{"version":3,"file":"cli.js","sources":["../src/actions/generate-models.ts","../src/actions/migrations-create.ts","../src/actions/migrations-update.ts","../src/actions/migrations-drops.ts","../src/cli.ts"],"sourcesContent":["import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { execSync } from \"child_process\";\n\n/**\n * Options for model generation\n */\ninterface GenerateModelsOptions {\n host: string;\n port: number;\n user: string;\n password: string;\n dbName: string;\n output: string;\n versionField: string;\n}\n\n/**\n * Interface for column metadata\n */\ninterface ColumnMetadata {\n autoincrement: boolean;\n name: string;\n type: string;\n primaryKey: boolean;\n notNull: boolean;\n}\n\n/**\n * Interface for table metadata\n */\ninterface TableMetadata {\n name: string;\n columns: Record<string, ColumnMetadata>;\n compositePrimaryKeys: Record<string, { name: string; columns: string[] }>;\n indexes: Record<string, any>;\n foreignKeys: Record<string, any>;\n uniqueConstraints: Record<string, any>;\n checkConstraint: Record<string, any>;\n}\n\n/**\n * Interface for version field metadata\n */\ninterface VersionFieldMetadata {\n fieldName: string;\n}\n\n/**\n * Interface for table version metadata\n */\ninterface TableVersionMetadata {\n tableName: string;\n versionField: VersionFieldMetadata;\n}\n\n/**\n * Type for additional metadata map\n */\ntype AdditionalMetadata = Record<string, TableVersionMetadata>;\n\n/**\n * Interface for journal entry\n */\ninterface JournalEntry {\n idx: number;\n version: string;\n when: number;\n tag: string;\n breakpoints: boolean;\n}\n\n/**\n * Interface for journal data\n */\ninterface JournalData {\n version: string;\n dialect: string;\n entries: JournalEntry[];\n}\n\n/**\n * Replaces MySQL types with custom types in the generated schema\n * @param schemaContent - The content of the generated schema file\n * @returns Modified schema content with custom types\n */\nfunction replaceMySQLTypes(schemaContent: string): string {\n // Add imports at the top of the file\n const imports = `import { forgeDateTimeString, forgeTimeString, forgeDateString, forgeTimestampString } from \"forge-sql-orm\";\\n\\n`;\n\n // Replace types in the content\n let modifiedContent = schemaContent\n // Handle datetime with column name and mode option\n .replace(\n /datetime\\(['\"]([^'\"]+)['\"],\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\)/g,\n \"forgeDateTimeString('$1')\",\n )\n // Handle datetime with column name only\n .replace(/datetime\\(['\"]([^'\"]+)['\"]\\)/g, \"forgeDateTimeString('$1')\")\n // Handle datetime with mode option only\n .replace(/datetime\\(\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\s*\\)/g, \"forgeDateTimeString()\")\n // Handle time with column name and mode option\n .replace(/time\\(['\"]([^'\"]+)['\"],\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\)/g, \"forgeTimeString('$1')\")\n // Handle time with column name only\n .replace(/time\\(['\"]([^'\"]+)['\"]\\)/g, \"forgeTimeString('$1')\")\n // Handle time with mode option only\n .replace(/time\\(\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\s*\\)/g, \"forgeTimeString()\")\n // Handle date with column name and mode option\n .replace(/date\\(['\"]([^'\"]+)['\"],\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\)/g, \"forgeDateString('$1')\")\n // Handle date with column name only\n .replace(/date\\(['\"]([^'\"]+)['\"]\\)/g, \"forgeDateString('$1')\")\n // Handle date with mode option only\n .replace(/date\\(\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\s*\\)/g, \"forgeDateString()\")\n // Handle timestamp with column name and mode option\n .replace(\n /timestamp\\(['\"]([^'\"]+)['\"],\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\)/g,\n \"forgeTimestampString('$1')\",\n )\n // Handle timestamp with column name only\n .replace(/timestamp\\(['\"]([^'\"]+)['\"]\\)/g, \"forgeTimestampString('$1')\")\n // Handle timestamp with mode option only\n .replace(/timestamp\\(\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\s*\\)/g, \"forgeTimestampString()\");\n\n // Add imports if they don't exist\n if (!modifiedContent.includes(\"import { forgeDateTimeString\")) {\n modifiedContent = imports + modifiedContent;\n }\n\n return modifiedContent;\n}\n\n/**\n * Generates models for all tables in the database using drizzle-kit\n * @param options - Generation options\n */\nexport const generateModels = async (options: GenerateModelsOptions) => {\n try {\n // Generate models using drizzle-kit pull\n await execSync(\n `npx drizzle-kit pull --dialect mysql --url mysql://${options.user}:${options.password}@${options.host}:${options.port}/${options.dbName} --out ${options.output}`,\n { encoding: \"utf-8\" },\n );\n\n // Process metadata to create version map\n const metaDir = path.join(options.output, \"meta\");\n const additionalMetadata: AdditionalMetadata = {};\n\n if (fs.existsSync(metaDir)) {\n const snapshotFile = path.join(metaDir, \"0000_snapshot.json\");\n if (fs.existsSync(snapshotFile)) {\n const snapshotData = JSON.parse(fs.readFileSync(snapshotFile, \"utf-8\"));\n\n // Process each table from the snapshot\n for (const [tableName, tableData] of Object.entries(snapshotData.tables)) {\n const table = tableData as TableMetadata;\n\n // Check if table name starts with 'a_' and warn about cache\n if (tableName.toLowerCase().startsWith(\"a_\")) {\n console.warn(\n `⚠️ Table \"${tableName}\" starts with \"a_\". KVS Cache will not work with this table because such tables are ignored in cache operations.`,\n );\n }\n\n // Find version field in columns\n const versionField = Object.entries(table.columns).find(\n ([_, col]) => col.name.toLowerCase() === options.versionField,\n );\n\n if (versionField) {\n const [_, col] = versionField;\n const fieldType = col.type;\n const isSupportedType =\n fieldType === \"datetime\" ||\n fieldType === \"timestamp\" ||\n fieldType === \"int\" ||\n fieldType === \"number\" ||\n fieldType === \"decimal\";\n if (!col.notNull) {\n console.warn(\n `Version field \"${col.name}\" in table ${tableName} is nullable. Versioning may not work correctly.`,\n );\n } else if (!isSupportedType) {\n console.warn(\n `Version field \"${col.name}\" in table ${tableName} has unsupported type \"${fieldType}\". ` +\n `Only datetime, timestamp, int, and decimal types are supported for versioning. Versioning will be skipped.`,\n );\n } else {\n additionalMetadata[tableName] = {\n tableName,\n versionField: {\n fieldName: col.name,\n },\n };\n }\n }\n }\n }\n }\n\n // Create version metadata file\n const versionMetadataContent = `/**\n * This file was auto-generated by forge-sql-orm\n * Generated at: ${new Date().toISOString()}\n * \n * DO NOT EDIT THIS FILE MANUALLY\n * Any changes will be overwritten on next generation\n */\n \n \nexport * from \"./relations\";\nexport * from \"./schema\";\n\nexport interface VersionFieldMetadata {\n fieldName: string;\n}\n\nexport interface TableMetadata {\n tableName: string;\n versionField: VersionFieldMetadata;\n}\n\nexport type AdditionalMetadata = Record<string, TableMetadata>;\n\nexport const additionalMetadata: AdditionalMetadata = ${JSON.stringify(additionalMetadata, null, 2)};\n`;\n\n fs.writeFileSync(path.join(options.output, \"index.ts\"), versionMetadataContent);\n\n // Replace MySQL types in the generated schema file\n const schemaPath = path.join(options.output, \"schema.ts\");\n if (fs.existsSync(schemaPath)) {\n const schemaContent = fs.readFileSync(schemaPath, \"utf-8\");\n const modifiedContent = replaceMySQLTypes(schemaContent);\n fs.writeFileSync(schemaPath, modifiedContent);\n console.log(`✅ Updated schema types in: ${schemaPath}`);\n }\n\n // Remove migration files and meta directory if they exist\n const migrationDir = path.join(options.output, \"migrations\");\n\n if (fs.existsSync(migrationDir)) {\n fs.rmSync(migrationDir, { recursive: true, force: true });\n console.log(`✅ Removed: ${migrationDir}`);\n }\n\n // Read journal and remove corresponding SQL file\n if (fs.existsSync(metaDir)) {\n const journalFile = path.join(metaDir, \"_journal.json\");\n if (fs.existsSync(journalFile)) {\n const journalData = JSON.parse(fs.readFileSync(journalFile, \"utf-8\")) as JournalData;\n\n // Remove SQL files for each entry\n for (const entry of journalData.entries) {\n const sqlFile = path.join(options.output, `${entry.tag}.sql`);\n if (fs.existsSync(sqlFile)) {\n fs.rmSync(sqlFile, { force: true });\n console.log(`✅ Removed SQL file: ${entry.tag}.sql`);\n }\n }\n }\n\n // Remove meta directory after processing\n fs.rmSync(metaDir, { recursive: true, force: true });\n console.log(`✅ Removed: ${metaDir}`);\n }\n\n console.log(`✅ Successfully generated models and version metadata`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error during model generation:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\n\nimport { execSync } from \"child_process\";\n\n/**\n * Options for migration creation\n */\nexport interface CreateMigrationOptions {\n output: string;\n entitiesPath: string;\n force?: boolean;\n}\n\n/**\n * Loads the current migration version from `migrationCount.ts`.\n * @param migrationPath - Path to the migration folder.\n * @returns The latest migration version.\n */\nexport const loadMigrationVersion = async (migrationPath: string): Promise<number> => {\n try {\n const migrationCountFilePath = path.resolve(path.join(migrationPath, \"migrationCount.ts\"));\n if (!fs.existsSync(migrationCountFilePath)) {\n console.log(`✅ Current migration version: 0`);\n return 0;\n }\n\n const { MIGRATION_VERSION } = await import(migrationCountFilePath);\n console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);\n return MIGRATION_VERSION as number;\n } catch (error) {\n console.error(`❌ Error loading migrationCount:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Cleans SQL statements by removing unnecessary database options.\n * @param sql - The raw SQL statement.\n * @returns The cleaned SQL statement.\n */\nexport function cleanSQLStatement(sql: string): string {\n // Add IF NOT EXISTS to CREATE TABLE statements\n sql = sql.replace(/create\\s+table\\s+(\\w+)/gi, \"create table if not exists $1\");\n\n // Add IF NOT EXISTS to CREATE INDEX statements\n sql = sql.replace(/create\\s+index\\s+(\\w+)/gi, \"create index if not exists $1\");\n\n // Add IF NOT EXISTS to ADD INDEX statements\n sql = sql.replace(\n /alter\\s+table\\s+(\\w+)\\s+add\\s+index\\s+(\\w+)/gi,\n \"alter table $1 add index if not exists $2\",\n );\n\n // Add IF NOT EXISTS to ADD CONSTRAINT statements\n sql = sql.replace(\n /alter\\s+table\\s+(\\w+)\\s+add\\s+constraint\\s+(\\w+)/gi,\n \"alter table $1 add constraint if not exists $2\",\n );\n\n // Remove unnecessary database options\n return sql.replace(/\\s+default\\s+character\\s+set\\s+utf8mb4\\s+engine\\s*=\\s*InnoDB;?/gi, \"\").trim();\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nexport function generateMigrationFile(createStatements: string[], version: number): string {\n const versionPrefix = `v${version}_MIGRATION`;\n\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map(\n (stmt, index) =>\n ` .enqueue(\"${versionPrefix}${index}\", \"${cleanSQLStatement(stmt).replace(/\\s+/g, \" \")}\")`,\n )\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n */\nexport function saveMigrationFiles(migrationCode: string, version: number, outputDir: string) {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file with static imports\n // Build import lines for each migration version\n const importLines = [];\n for (let i = 1; i <= version; i++) {\n importLines.push(`import v${i} from \"./migrationV${i}\";`);\n }\n // Build call lines for each migration version\n const callLines = [];\n for (let i = 1; i <= version; i++) {\n callLines.push(` v${i}(migrationRunner);`);\n }\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\n${importLines.join(\"\\n\")}\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n${callLines.join(\"\\n\")}\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n}\n\n/**\n * Extracts only the relevant SQL statements for migration.\n * @param schema - The full database schema as SQL.\n * @returns Filtered list of SQL statements.\n */\nexport const extractCreateStatements = (schema: string): string[] => {\n // Split by statement-breakpoint and semicolon\n const statements = schema\n .split(/--> statement-breakpoint|;/)\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n\n return statements.filter(\n (stmt) =>\n stmt.toLowerCase().startsWith(\"create table\") ||\n stmt.toLowerCase().startsWith(\"alter table\") ||\n stmt.toLowerCase().includes(\"add index\") ||\n stmt.toLowerCase().includes(\"create index\") ||\n stmt.toLowerCase().includes(\"add unique index\") ||\n stmt.toLowerCase().includes(\"add constraint\"),\n );\n};\n\n/**\n * Creates a full database migration.\n * @param options - Database connection settings and output paths.\n */\nexport const createMigration = async (options: CreateMigrationOptions) => {\n try {\n let version = await loadMigrationVersion(options.output);\n\n if (version > 0) {\n if (options.force) {\n console.warn(\n `⚠️ Warning: Migration already exists. Creating new migration with force flag...`,\n );\n } else {\n console.error(\n `❌ Error: Migration has already been created. Use --force flag to override.`,\n );\n process.exit(1);\n }\n }\n\n // Generate SQL using drizzle-kit\n await execSync(\n `npx drizzle-kit generate --name=init --dialect mysql --out ${options.output} --schema ${options.entitiesPath}`,\n { encoding: \"utf-8\" },\n );\n const initSqlFile = path.join(options.output, \"0000_init.sql\");\n const sql = fs.readFileSync(initSqlFile, \"utf-8\");\n\n // Extract and clean statements\n const createStatements = extractCreateStatements(sql);\n\n // Generate and save migration files\n const migrationFile = generateMigrationFile(createStatements, 1);\n saveMigrationFiles(migrationFile, 1, options.output);\n\n fs.rmSync(initSqlFile, { force: true });\n console.log(`✅ Removed SQL file: ${initSqlFile}`);\n // Remove meta directory after processing\n let metaDir = path.join(options.output, \"meta\");\n fs.rmSync(metaDir, { recursive: true, force: true });\n console.log(`✅ Removed: ${metaDir}`);\n console.log(`✅ Migration successfully created!`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error during migration creation:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport mysql from \"mysql2/promise\";\nimport { MySqlTable, TableConfig } from \"drizzle-orm/mysql-core\";\nimport { RowDataPacket } from \"mysql2\";\nimport { getTableMetadata } from \"forge-sql-orm\";\nimport { AnyIndexBuilder } from \"drizzle-orm/mysql-core/indexes\";\nimport { ForeignKeyBuilder } from \"drizzle-orm/mysql-core/foreign-keys\";\nimport { UniqueConstraintBuilder } from \"drizzle-orm/mysql-core/unique-constraint\";\n\ninterface DrizzleColumn {\n type: string;\n notNull: boolean;\n autoincrement?: boolean;\n columnType?: any;\n name: string;\n getSQLType: () => string;\n}\n\ninterface DrizzleSchema {\n [tableName: string]: {\n [columnName: string]: DrizzleColumn;\n };\n}\n\ninterface DatabaseColumn extends RowDataPacket {\n TABLE_NAME: string;\n COLUMN_NAME: string;\n COLUMN_TYPE: string;\n IS_NULLABLE: string;\n COLUMN_KEY: string;\n EXTRA: string;\n}\n\ninterface DatabaseIndex extends RowDataPacket {\n TABLE_NAME: string;\n INDEX_NAME: string;\n COLUMN_NAME: string;\n NON_UNIQUE: number;\n}\n\ninterface DatabaseForeignKey extends RowDataPacket {\n TABLE_NAME: string;\n COLUMN_NAME: string;\n CONSTRAINT_NAME: string;\n REFERENCED_TABLE_NAME: string;\n REFERENCED_COLUMN_NAME: string;\n}\n\ninterface TableSchema {\n columns: Record<string, DatabaseColumn>;\n indexes: Record<\n string,\n {\n columns: string[];\n unique: boolean;\n }\n >;\n foreignKeys: Record<\n string,\n {\n column: string;\n referencedTable: string;\n referencedColumn: string;\n }\n >;\n}\n\ninterface DatabaseSchema {\n [tableName: string]: TableSchema;\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nfunction generateMigrationFile(createStatements: string[], version: number): string {\n const versionPrefix = `v${version}_MIGRATION`;\n\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map((stmt, index) => ` .enqueue(\"${versionPrefix}${index}\", \"${stmt}\")`)\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Filters out SQL statements that already exist in the previous migration file\n * @param newStatements - Array of SQL statements from new migration\n * @param prevVersion - Previous migration version\n * @param outputDir - Directory where migration files are stored\n * @returns Array of SQL statements that don't exist in previous migration\n */\nfunction filterWithPreviousMigration(\n newStatements: string[],\n prevVersion: number,\n outputDir: string,\n): string[] {\n const prevMigrationPath = path.join(outputDir, `migrationV${prevVersion}.ts`);\n\n if (!fs.existsSync(prevMigrationPath)) {\n return newStatements.map((s) => s.replace(/\\s+/g, \" \"));\n }\n\n // Read previous migration file\n const prevContent = fs.readFileSync(prevMigrationPath, \"utf-8\");\n\n // Extract SQL statements from the file\n const prevStatements = prevContent\n .split(\"\\n\")\n .filter((line) => line.includes(\".enqueue(\"))\n .map((line) => {\n const match = line.match(/\\.enqueue\\([^,]+,\\s*\"([^\"]+)\"/);\n return match ? match[1].replace(/\\s+/g, \" \").trim() : \"\";\n });\n\n // Filter out statements that already exist in previous migration\n return newStatements\n .filter((s) => !prevStatements.includes(s.replace(/\\s+/g, \" \")))\n .map((s) => s.replace(/\\s+/g, \" \"));\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n * @returns boolean indicating if migration was saved\n */\nfunction saveMigrationFiles(migrationCode: string, version: number, outputDir: string): boolean {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\nimport { MIGRATION_VERSION } from \"./migrationCount\";\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n for (let i = 1; i <= MIGRATION_VERSION; i++) {\n const migrations = (await import(\\`./migrationV\\${i}\\`)) as {\n default: MigrationType;\n };\n migrations.default(migrationRunner);\n }\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n\n return true;\n}\n\n/**\n * Loads the current migration version from `migrationCount.ts`.\n * @param migrationPath - Path to the migration folder.\n * @returns The latest migration version.\n */\nconst loadMigrationVersion = async (migrationPath: string): Promise<number> => {\n try {\n const migrationCountFilePath = path.resolve(path.join(migrationPath, \"migrationCount.ts\"));\n if (!fs.existsSync(migrationCountFilePath)) {\n console.warn(\n `⚠️ Warning: migrationCount.ts not found in ${migrationCountFilePath}, assuming no previous migrations.`,\n );\n return 0;\n }\n\n const { MIGRATION_VERSION } = await import(migrationCountFilePath);\n console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);\n return MIGRATION_VERSION as number;\n } catch (error) {\n console.error(`❌ Error loading migrationCount:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Gets the current database schema from MySQL including indexes and foreign keys\n * @param connection - MySQL connection\n * @param dbName - Database name\n * @returns Database schema object with indexes and foreign keys\n */\nasync function getDatabaseSchema(\n connection: mysql.Connection,\n dbName: string,\n): Promise<DatabaseSchema> {\n // Get columns\n const [columns] = await connection.execute<DatabaseColumn[]>(\n `\n SELECT TABLE_NAME, COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY, EXTRA\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_SCHEMA = ?\n `,\n [dbName],\n );\n\n // Get indexes\n const [indexes] = await connection.execute<DatabaseIndex[]>(\n `\n SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, NON_UNIQUE\n FROM INFORMATION_SCHEMA.STATISTICS\n WHERE TABLE_SCHEMA = ?\n ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX\n `,\n [dbName],\n );\n\n // Get foreign keys\n const [foreignKeys] = await connection.execute<DatabaseForeignKey[]>(\n `\n SELECT \n TABLE_NAME,\n COLUMN_NAME,\n CONSTRAINT_NAME,\n REFERENCED_TABLE_NAME,\n REFERENCED_COLUMN_NAME\n FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE\n WHERE TABLE_SCHEMA = ?\n AND REFERENCED_TABLE_NAME IS NOT NULL\n `,\n [dbName],\n );\n\n const schema: DatabaseSchema = {};\n\n // Process columns\n columns.forEach((row) => {\n if (!schema[row.TABLE_NAME]) {\n schema[row.TABLE_NAME] = {\n columns: {},\n indexes: {},\n foreignKeys: {},\n };\n }\n schema[row.TABLE_NAME].columns[row.COLUMN_NAME] = row;\n });\n\n // Process indexes\n indexes.forEach((row) => {\n if (!schema[row.TABLE_NAME].indexes[row.INDEX_NAME]) {\n schema[row.TABLE_NAME].indexes[row.INDEX_NAME] = {\n columns: [],\n unique: !row.NON_UNIQUE,\n };\n }\n schema[row.TABLE_NAME].indexes[row.INDEX_NAME].columns.push(row.COLUMN_NAME);\n });\n\n // Process foreign keys\n foreignKeys.forEach((row) => {\n if (!schema[row.TABLE_NAME].foreignKeys[row.CONSTRAINT_NAME]) {\n schema[row.TABLE_NAME].foreignKeys[row.CONSTRAINT_NAME] = {\n column: row.COLUMN_NAME,\n referencedTable: row.REFERENCED_TABLE_NAME,\n referencedColumn: row.REFERENCED_COLUMN_NAME,\n };\n }\n });\n\n return schema;\n}\n\n/**\n * Converts MySQL type to normalized format for comparison\n * @param mysqlType - MySQL type from INFORMATION_SCHEMA or Drizzle type\n * @returns Normalized type string\n */\nfunction normalizeMySQLType(mysqlType: string): string {\n // Remove length/precision information\n let normalized = mysqlType.replace(/\\([^)]*\\)/, \"\").toLowerCase();\n\n // Remove 'mysql' prefix from Drizzle types\n normalized = normalized.replace(/^mysql/, \"\");\n\n return normalized;\n}\n\n/**\n * Gets the name of a foreign key constraint\n * @param fk - The foreign key builder\n * @returns The name of the foreign key constraint\n */\nfunction getForeignKeyName(fk: ForeignKeyBuilder): string {\n // @ts-ignore - Internal property access\n return fk.name;\n}\n\n/**\n * Gets the name of an index\n * @param index - The index builder\n * @returns The name of the index\n */\nfunction getIndexName(index: AnyIndexBuilder): string {\n // @ts-ignore - Internal property access\n return index.name;\n}\n\n/**\n * Gets the name of a unique constraint\n * @param uc - The unique constraint builder\n * @returns The name of the unique constraint\n */\nfunction getUniqueConstraintName(uc: UniqueConstraintBuilder): string {\n // @ts-ignore - Internal property access\n return uc.name;\n}\n\n/**\n * Gets the columns of an index\n * @param index - The index builder\n * @returns Array of column names\n */\nfunction getIndexColumns(index: AnyIndexBuilder): string[] {\n // @ts-ignore - Internal property access\n return index.columns.map((col) => col.name);\n}\n\nfunction compareForeignKey(\n fk: ForeignKeyBuilder,\n { columns }: { columns: string[]; unique: boolean },\n) {\n // @ts-ignore\n const fcolumns: string[] = fk.columns.map((c) => c.name);\n return fcolumns.sort().join(\",\") === columns.sort().join(\",\");\n}\n\n/**\n * Generates SQL changes by comparing Drizzle schema with database schema\n * @param drizzleSchema - Schema from Drizzle\n * @param dbSchema - Schema from database\n * @param schemaModule - Drizzle schema module\n * @returns Array of SQL statements\n */\nfunction generateSchemaChanges(\n drizzleSchema: DrizzleSchema,\n dbSchema: DatabaseSchema,\n schemaModule: Record<string, any>,\n): string[] {\n const changes: string[] = [];\n\n // First check existing tables in database\n for (const [tableName, dbTable] of Object.entries(dbSchema)) {\n const drizzleColumns = drizzleSchema[tableName];\n\n if (!drizzleColumns) {\n // Table exists in database but not in schema - create it\n const columns = Object.entries(dbTable.columns)\n .map(([colName, col]) => {\n const type = col.COLUMN_TYPE;\n const nullable = col.IS_NULLABLE === \"YES\" ? \"NULL\" : \"NOT NULL\";\n const autoIncrement = col.EXTRA.includes(\"auto_increment\") ? \"AUTO_INCREMENT\" : \"\";\n return `\\`${colName}\\` ${type} ${nullable} ${autoIncrement}`.trim();\n })\n .join(\",\\n \");\n\n changes.push(`CREATE TABLE if not exists \\`${tableName}\\` (\\n ${columns}\\n);`);\n\n // Create indexes for new table\n for (const [indexName, dbIndex] of Object.entries(dbTable.indexes)) {\n // Skip primary key and foreign key indexes\n if (indexName === \"PRIMARY\") {\n continue;\n }\n\n // Check if any column in this index is a foreign key\n const isForeignKeyIndex = dbIndex.columns.some((colName) => {\n const column = dbTable.columns[colName];\n return column && column.COLUMN_KEY === \"MUL\" && column.EXTRA.includes(\"foreign key\");\n });\n\n if (isForeignKeyIndex) {\n continue;\n }\n\n // Create index\n const columns = dbIndex.columns.map((col) => `\\`${col}\\``).join(\", \");\n const unique = dbIndex.unique ? \"UNIQUE \" : \"\";\n changes.push(\n `CREATE ${unique}INDEX if not exists \\`${indexName}\\` ON \\`${tableName}\\` (${columns});`,\n );\n }\n\n // Create foreign keys for new table\n for (const [fkName, dbFK] of Object.entries(dbTable.foreignKeys)) {\n changes.push(\n `ALTER TABLE \\`${tableName}\\` ADD CONSTRAINT \\`${fkName}\\` FOREIGN KEY (\\`${dbFK.column}\\`) REFERENCES \\`${dbFK.referencedTable}\\` (\\`${dbFK.referencedColumn}\\`);`,\n );\n }\n continue;\n }\n\n // Check for column changes in existing tables\n for (const [colName, dbCol] of Object.entries(dbTable.columns)) {\n const drizzleCol = Object.values(drizzleColumns).find((c) => c.name === colName);\n\n if (!drizzleCol) {\n // Column exists in database but not in schema - create it\n const type = dbCol.COLUMN_TYPE;\n const nullable = dbCol.IS_NULLABLE === \"YES\" ? \"NULL\" : \"NOT NULL\";\n changes.push(`ALTER TABLE \\`${tableName}\\` ADD COLUMN IF NOT EXISTS \\`${colName}\\` ${type} ${nullable};`);\n continue;\n }\n\n // Check for type changes\n const normalizedDbType = normalizeMySQLType(dbCol.COLUMN_TYPE);\n const normalizedDrizzleType = normalizeMySQLType(drizzleCol.getSQLType());\n\n if (normalizedDbType !== normalizedDrizzleType) {\n const type = dbCol.COLUMN_TYPE; // Use database type as source of truth\n const nullable = dbCol.IS_NULLABLE === \"YES\" ? \"NULL\" : \"NOT NULL\";\n changes.push(\n `ALTER TABLE \\`${tableName}\\` MODIFY COLUMN \\`${colName}\\` IF EXISTS ${type} ${nullable};`,\n );\n }\n }\n\n // Check for index changes\n const table = Object.values(schemaModule).find((t) => {\n const metadata = getTableMetadata(t);\n return metadata.tableName === tableName;\n });\n\n if (table) {\n const metadata = getTableMetadata(table);\n // First check indexes that exist in database but not in schema\n for (const [indexName, dbIndex] of Object.entries(dbTable.indexes)) {\n // Skip primary key and foreign key indexes\n if (indexName === \"PRIMARY\") {\n continue;\n }\n\n // Check if this is a foreign key index\n const isForeignKeyIndex = metadata.foreignKeys.some(\n (fk) => getForeignKeyName(fk) === indexName || compareForeignKey(fk, dbIndex),\n );\n if (isForeignKeyIndex) {\n continue;\n }\n\n // Check if this is a unique constraint\n const existsUniqIndex = metadata.uniqueConstraints.find(\n (uc) => getUniqueConstraintName(uc) === indexName,\n );\n let drizzleIndex = metadata.indexes.find((i) => getIndexName(i) === indexName);\n\n if (!drizzleIndex && existsUniqIndex) {\n drizzleIndex = existsUniqIndex as unknown as AnyIndexBuilder;\n }\n\n if (!drizzleIndex) {\n // Index exists in database but not in schema - create it\n const columns = dbIndex.columns.map((col) => `\\`${col}\\``).join(\", \");\n const unique = dbIndex.unique ? \"UNIQUE \" : \"\";\n changes.push(\n `CREATE ${unique}INDEX if not exists \\`${indexName}\\` ON \\`${tableName}\\` (${columns});`,\n );\n continue;\n }\n\n // Check if index columns changed\n const dbColumns = dbIndex.columns.join(\", \");\n const drizzleColumns = getIndexColumns(drizzleIndex).join(\", \");\n if (\n dbColumns !== drizzleColumns ||\n dbIndex.unique !== drizzleIndex instanceof UniqueConstraintBuilder\n ) {\n // Drop and recreate index using database values\n changes.push(`DROP INDEX \\`${indexName}\\` ON \\`${tableName}\\`;`);\n const columns = dbIndex.columns.map((col) => `\\`${col}\\``).join(\", \");\n const unique = dbIndex.unique ? \"UNIQUE \" : \"\";\n changes.push(\n `CREATE ${unique}INDEX if not exists \\`${indexName}\\` ON \\`${tableName}\\` (${columns});`,\n );\n }\n }\n\n // First check foreign keys that exist in database but not in schema\n for (const [fkName, dbFK] of Object.entries(dbTable.foreignKeys)) {\n // Find if this column is referenced in Drizzle schema\n const drizzleFK = metadata.foreignKeys.find(\n (fk) =>\n getForeignKeyName(fk) === fkName ||\n compareForeignKey(fk, { columns: [dbFK.column], unique: false }),\n );\n\n if (!drizzleFK) {\n // Foreign key exists in database but not in schema - drop it\n changes.push(\n `ALTER TABLE \\`${tableName}\\` ADD CONSTRAINT \\`${fkName}\\` FOREIGN KEY (\\`${dbFK.column}\\`) REFERENCES \\`${dbFK.referencedTable}\\` (\\`${dbFK.referencedColumn}\\`);`,\n );\n continue;\n }\n }\n\n // Then check for new foreign keys that exist in schema but not in database\n for (const drizzleForeignKey of metadata.foreignKeys) {\n // Find if this foreign key exists in database\n const isDbFk = Object.keys(dbTable.foreignKeys).find((fk) => {\n let foreignKey = dbTable.foreignKeys[fk];\n return (\n fk === getForeignKeyName(drizzleForeignKey) ||\n compareForeignKey(drizzleForeignKey, { columns: [foreignKey.column], unique: false })\n );\n });\n\n if (!isDbFk) {\n // Foreign key exists in schema but not in database - create it\n if (drizzleForeignKey) {\n const fkName = getForeignKeyName(drizzleForeignKey);\n if (fkName) {\n changes.push(`ALTER TABLE \\`${tableName}\\` DROP FOREIGN KEY \\`${fkName}\\`;`);\n } else {\n // @ts-ignore\n const columns = drizzleForeignKey.columns;\n const columnNames = columns?.length\n ? columns.map((c: any) => c.name).join(\", \")\n : \"unknown columns\";\n console.warn(\n `⚠️ Drizzle model for table '${tableName}' does not provide a name for FOREIGN KEY constraint on columns: ${columnNames}`,\n );\n }\n }\n }\n }\n }\n }\n\n return changes;\n}\n\n/**\n * Updates an existing database migration by generating schema modifications.\n * @param options - Database connection settings and output paths.\n */\nexport const updateMigration = async (options: any) => {\n try {\n let version = await loadMigrationVersion(options.output);\n const prevVersion = version;\n\n if (version < 1) {\n console.log(\n `⚠️ Initial migration not found. Run \"npx forge-sql-orm migrations:create\" first.`,\n );\n process.exit(0);\n }\n version += 1;\n\n // Create database connection\n const connection = await mysql.createConnection({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n database: options.dbName,\n });\n\n try {\n // Get current database schema\n const dbSchema = await getDatabaseSchema(connection, options.dbName);\n\n // Import Drizzle schema using absolute path\n const schemaPath = path.resolve(options.entitiesPath, \"schema.ts\");\n if (!fs.existsSync(schemaPath)) {\n throw new Error(`Schema file not found at: ${schemaPath}`);\n }\n\n const schemaModule = await import(schemaPath);\n if (!schemaModule) {\n throw new Error(`Invalid schema file at: ${schemaPath}. Schema must export tables.`);\n }\n\n // Process exported tables\n const drizzleSchema: DrizzleSchema = {};\n\n // Get all exports that are tables\n const tables = Object.values(schemaModule) as MySqlTable<TableConfig>[];\n\n tables.forEach((table) => {\n const metadata = getTableMetadata(table);\n if (metadata.tableName) {\n // Convert AnyColumn to DrizzleColumn\n const columns: Record<string, DrizzleColumn> = {};\n Object.entries(metadata.columns).forEach(([name, column]) => {\n columns[name] = {\n type: column.dataType,\n notNull: column.notNull,\n autoincrement: (column as any).autoincrement,\n columnType: column.columnType,\n name: column.name,\n getSQLType: () => column.getSQLType(),\n };\n });\n drizzleSchema[metadata.tableName] = columns;\n }\n });\n\n if (Object.keys(drizzleSchema).length === 0) {\n throw new Error(`No valid tables found in schema at: ${schemaPath}`);\n }\n\n console.log(\"Found tables:\", Object.keys(drizzleSchema));\n\n // Generate SQL changes\n const createStatements = filterWithPreviousMigration(\n generateSchemaChanges(drizzleSchema, dbSchema, schemaModule),\n prevVersion,\n options.output,\n );\n\n if (createStatements.length) {\n // Generate migration file content\n const migrationFile = generateMigrationFile(createStatements, version);\n\n // Save migration files only if there are actual changes\n if (saveMigrationFiles(migrationFile, version, options.output)) {\n console.log(`✅ Migration successfully updated!`);\n }\n process.exit(0);\n } else {\n console.log(`⚠️ No new migration changes detected.`);\n process.exit(0);\n }\n } finally {\n await connection.end();\n }\n } catch (error) {\n console.error(`❌ Error during migration update:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { MySqlTable, TableConfig } from \"drizzle-orm/mysql-core\";\nimport { getTableMetadata, generateDropTableStatements } from \"forge-sql-orm\";\n\n/**\n * Generates a migration ID using current date\n * @returns Migration ID string with current date\n */\nfunction generateMigrationUUID(version: number): string {\n const now = new Date();\n const timestamp = now.getTime();\n return `MIGRATION_V${version}_${timestamp}`;\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nfunction generateMigrationFile(createStatements: string[], version: number): string {\n const uniqId = generateMigrationUUID(version);\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map(\n (stmt, index) => ` .enqueue(\"${uniqId}_${index}\", \\\"${stmt}\\\")`, // eslint-disable-line no-useless-escape\n )\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n */\nfunction saveMigrationFiles(migrationCode: string, version: number, outputDir: string) {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\nimport { MIGRATION_VERSION } from \"./migrationCount\";\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n for (let i = 1; i <= MIGRATION_VERSION; i++) {\n const migrations = (await import(\\`./migrationV\\${i}\\`)) as {\n default: MigrationType;\n };\n migrations.default(migrationRunner);\n }\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n}\n\n/**\n * Creates a full database migration.\n * @param options - Database connection settings and output paths.\n */\nexport const dropMigration = async (options: any) => {\n try {\n // Start from version 1 if no previous migrations exist\n const version = 1;\n\n // Import Drizzle schema using absolute path\n const schemaPath = path.resolve(options.entitiesPath, \"schema.ts\");\n if (!fs.existsSync(schemaPath)) {\n throw new Error(`Schema file not found at: ${schemaPath}`);\n }\n\n const schemaModule = await import(schemaPath);\n if (!schemaModule) {\n throw new Error(`Invalid schema file at: ${schemaPath}. Schema must export tables.`);\n }\n\n // Get all exports that are tables\n const tables = Object.values(schemaModule) as MySqlTable<TableConfig>[];\n\n if (tables.length === 0) {\n throw new Error(`No valid tables found in schema at: ${schemaPath}`);\n }\n\n // Get table names for logging\n const tableNames = tables\n .map((table) => {\n const metadata = getTableMetadata(table);\n return metadata.tableName;\n })\n .filter(Boolean);\n\n console.log(\"Found tables:\", tableNames);\n\n // Generate drop statements\n const dropStatements = generateDropTableStatements(tableNames);\n\n // Generate and save migration files\n const migrationFile = generateMigrationFile(dropStatements, version);\n saveMigrationFiles(migrationFile, version, options.output);\n\n console.log(`✅ Migration successfully created!`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error during migration creation:`, error);\n process.exit(1);\n }\n};\n","#!/usr/bin/env node\n\nimport { Command } from \"commander\";\nimport dotenv from \"dotenv\";\nimport inquirer from \"inquirer\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { generateModels } from \"./actions/generate-models\";\nimport { createMigration } from \"./actions/migrations-create\";\nimport { updateMigration } from \"./actions/migrations-update\";\nimport { dropMigration } from \"./actions/migrations-drops\";\n\nconst ENV_PATH = path.resolve(process.cwd(), \".env\");\n// 🔄 Load environment variables from `.env` file\ndotenv.config({ path: ENV_PATH });\n\nconst saveEnvFile = (config: any) => {\n let envContent = \"\";\n const envFilePath = ENV_PATH;\n\n if (fs.existsSync(envFilePath)) {\n envContent = fs.readFileSync(envFilePath, \"utf8\");\n }\n\n const envVars = envContent\n .split(\"\\n\")\n .filter((line) => line.trim() !== \"\" && !line.startsWith(\"#\"))\n .reduce((acc: any, line) => {\n const [key, ...value] = line.split(\"=\");\n acc[key] = value.join(\"=\");\n return acc;\n }, {});\n\n Object.entries(config).forEach(([key, value]) => {\n envVars[`FORGE_SQL_ORM_${key.toUpperCase()}`] = value;\n });\n\n const updatedEnvContent = Object.entries(envVars)\n .map(([key, value]) => `${key}=${value}`)\n .join(\"\\n\");\n\n fs.writeFileSync(envFilePath, updatedEnvContent, { encoding: \"utf8\" });\n\n console.log(\"✅ Configuration saved to .env without overwriting other variables.\");\n};\n\n/**\n * Prompts the user for missing parameters using Inquirer.js.\n * @param config - The current configuration object.\n * @param defaultOutput - Default output path.\n * @param customAskMissingParams - Optional function for additional prompts.\n * @returns Updated configuration with user input.\n */\nconst askMissingParams = async (\n config: any,\n defaultOutput: string,\n customAskMissingParams?: (cfg: any, questions: unknown[]) => void,\n) => {\n const questions: unknown[] = [];\n\n if (!config.host)\n questions.push({\n type: \"input\",\n name: \"host\",\n message: \"Enter database host:\",\n default: \"localhost\",\n });\n\n if (!config.port)\n questions.push({\n type: \"input\",\n name: \"port\",\n message: \"Enter database port:\",\n default: \"3306\",\n validate: (input: string) => !isNaN(parseInt(input, 10)),\n });\n\n if (!config.user)\n questions.push({\n type: \"input\",\n name: \"user\",\n message: \"Enter database user:\",\n default: \"root\",\n });\n\n if (!config.password)\n questions.push({\n type: \"password\",\n name: \"password\",\n message: \"Enter database password:\",\n mask: \"*\",\n });\n\n if (!config.dbName)\n questions.push({\n type: \"input\",\n name: \"dbName\",\n message: \"Enter database name:\",\n });\n\n if (!config.output)\n questions.push({\n type: \"input\",\n name: \"output\",\n message: \"Enter output path:\",\n default: defaultOutput,\n });\n\n // Allow additional questions from the caller\n if (customAskMissingParams) {\n customAskMissingParams(config, questions);\n }\n\n // If there are missing parameters, prompt the user\n if (questions.length > 0) {\n // @ts-ignore - Ignore TypeScript warning for dynamic question type\n const answers = await inquirer.prompt(questions);\n return { ...config, ...answers, port: parseInt(config.port ?? answers.port, 10) };\n }\n\n return config;\n};\n\n/**\n * Retrieves configuration parameters from command-line arguments and environment variables.\n * If any required parameters are missing, prompts the user for input.\n * @param cmd - The command object containing CLI options.\n * @param defaultOutput - Default output directory.\n * @param customConfig - Optional function for additional configuration parameters.\n * @param customAskMissingParams - Optional function for additional prompts.\n * @returns A fully resolved configuration object.\n */\nconst getConfig = async (\n cmd: any,\n defaultOutput: string,\n customConfig?: () => any,\n customAskMissingParams?: (cfg: any, questions: unknown[]) => void,\n) => {\n let config = {\n host: cmd.host || process.env.FORGE_SQL_ORM_HOST,\n port: cmd.port\n ? parseInt(cmd.port, 10)\n : process.env.FORGE_SQL_ORM_PORT\n ? parseInt(process.env.FORGE_SQL_ORM_PORT, 10)\n : undefined,\n user: cmd.user || process.env.FORGE_SQL_ORM_USER,\n password: cmd.password || process.env.FORGE_SQL_ORM_PASSWORD,\n dbName: cmd.dbName || process.env.FORGE_SQL_ORM_DBNAME,\n output: cmd.output || process.env.FORGE_SQL_ORM_OUTPUT,\n };\n\n // Merge additional configurations if provided\n if (customConfig) {\n config = { ...config, ...customConfig() };\n }\n\n const conf = await askMissingParams(config, defaultOutput, customAskMissingParams);\n if (cmd.saveEnv) {\n saveEnvFile(conf);\n }\n return conf;\n};\n\n// 📌 Initialize CLI\nexport const program = new Command();\nprogram.version(\"1.0.0\");\n\n// ✅ Command: Generate database models (Entities)\nprogram\n .command(\"generate:model\")\n .description(\"Generate Drizzle models from the database.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for entities\")\n .option(\"--versionField <string>\", \"Field name for versioning\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/entities\",\n () => ({\n versionField: cmd.versionField || process.env.FORGE_SQL_ORM_VERSIONFIELD,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.versionField) {\n questions.push({\n type: \"input\",\n name: \"versionField\",\n message: \"Enter the field name for versioning (leave empty to skip):\",\n default: \"\",\n });\n }\n },\n );\n await generateModels(config);\n });\n\n// ✅ Command: Create initial database migration\nprogram\n .command(\"migrations:create\")\n .description(\"Generate an initial migration for the entire database.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--force\", \"Force creation even if migrations exist\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n force: cmd.force || false,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await createMigration(config);\n });\n\n// ✅ Command: Update migration for schema changes\nprogram\n .command(\"migrations:update\")\n .description(\"Generate a migration to update the database schema.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await updateMigration(config);\n });\n\n// ✅ Command: Drop all migrations\nprogram\n .command(\"migrations:drop\")\n .description(\"Generate a migration to drop all tables and clear migrations history.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await dropMigration(config);\n });\n\n// 🔥 Execute CLI\n program.parse(process.argv);\n"],"names":["execSync","loadMigrationVersion","generateMigrationFile","saveMigrationFiles","columns","getTableMetadata","drizzleColumns","UniqueConstraintBuilder","generateDropTableStatements","Command"],"mappings":";;;;;;;;;;;;;AAuFA,SAAS,kBAAkB,eAA+B;AAExD,QAAM,UAAU;AAAA;AAAA;AAGhB,MAAI,kBAAkB,cAEnB;AAAA,IACC;AAAA,IACA;AAAA,EAAA,EAGD,QAAQ,iCAAiC,2BAA2B,EAEpE,QAAQ,qDAAqD,uBAAuB,EAEpF,QAAQ,+DAA+D,uBAAuB,EAE9F,QAAQ,6BAA6B,uBAAuB,EAE5D,QAAQ,iDAAiD,mBAAmB,EAE5E,QAAQ,+DAA+D,uBAAuB,EAE9F,QAAQ,6BAA6B,uBAAuB,EAE5D,QAAQ,iDAAiD,mBAAmB,EAE5E;AAAA,IACC;AAAA,IACA;AAAA,EAAA,EAGD,QAAQ,kCAAkC,4BAA4B,EAEtE,QAAQ,sDAAsD,wBAAwB;AAGzF,MAAI,CAAC,gBAAgB,SAAS,8BAA8B,GAAG;AAC7D,sBAAkB,UAAU;AAAA,EAC9B;AAEA,SAAO;AACT;AAMO,MAAM,iBAAiB,OAAO,YAAmC;AACtE,MAAI;AAEF,UAAMA,cAAAA;AAAAA,MACJ,sDAAsD,QAAQ,IAAI,IAAI,QAAQ,QAAQ,IAAI,QAAQ,IAAI,IAAI,QAAQ,IAAI,IAAI,QAAQ,MAAM,UAAU,QAAQ,MAAM;AAAA,MAChK,EAAE,UAAU,QAAA;AAAA,IAAQ;AAItB,UAAM,UAAU,KAAK,KAAK,QAAQ,QAAQ,MAAM;AAChD,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AAyB;AAC7B,UAAI,CAAC,IAAI;AACP,kBAAU,KAAK;AAAA,UACb,MAAM;AAAA,UACN,MAAM;AAAA,UACN,SAAS;AAAA,UACT,SAAS;AAAA,QAAA,CACV;AAAA,IACL;AAAA,EAAA;AAEF,QAAM,cAAc,MAAM;AAC5B,CAAC;AAGD,QAAQ,MAAM,QAAQ,IAAI;;"}
|
package/dist-cli/cli.mjs
CHANGED
|
@@ -39,6 +39,11 @@ const generateModels = async (options) => {
|
|
|
39
39
|
const snapshotData = JSON.parse(fs.readFileSync(snapshotFile, "utf-8"));
|
|
40
40
|
for (const [tableName, tableData] of Object.entries(snapshotData.tables)) {
|
|
41
41
|
const table = tableData;
|
|
42
|
+
if (tableName.toLowerCase().startsWith("a_")) {
|
|
43
|
+
console.warn(
|
|
44
|
+
`⚠️ Table "${tableName}" starts with "a_". KVS Cache will not work with this table because such tables are ignored in cache operations.`
|
|
45
|
+
);
|
|
46
|
+
}
|
|
42
47
|
const versionField = Object.entries(table.columns).find(
|
|
43
48
|
([_, col]) => col.name.toLowerCase() === options.versionField
|
|
44
49
|
);
|
package/dist-cli/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.mjs","sources":["../src/actions/generate-models.ts","../src/actions/migrations-create.ts","../src/actions/migrations-update.ts","../src/actions/migrations-drops.ts","../src/cli.ts"],"sourcesContent":["import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { execSync } from \"child_process\";\n\n/**\n * Options for model generation\n */\ninterface GenerateModelsOptions {\n host: string;\n port: number;\n user: string;\n password: string;\n dbName: string;\n output: string;\n versionField: string;\n}\n\n/**\n * Interface for column metadata\n */\ninterface ColumnMetadata {\n autoincrement: boolean;\n name: string;\n type: string;\n primaryKey: boolean;\n notNull: boolean;\n}\n\n/**\n * Interface for table metadata\n */\ninterface TableMetadata {\n name: string;\n columns: Record<string, ColumnMetadata>;\n compositePrimaryKeys: Record<string, { name: string; columns: string[] }>;\n indexes: Record<string, any>;\n foreignKeys: Record<string, any>;\n uniqueConstraints: Record<string, any>;\n checkConstraint: Record<string, any>;\n}\n\n/**\n * Interface for version field metadata\n */\ninterface VersionFieldMetadata {\n fieldName: string;\n}\n\n/**\n * Interface for table version metadata\n */\ninterface TableVersionMetadata {\n tableName: string;\n versionField: VersionFieldMetadata;\n}\n\n/**\n * Type for additional metadata map\n */\ntype AdditionalMetadata = Record<string, TableVersionMetadata>;\n\n/**\n * Interface for journal entry\n */\ninterface JournalEntry {\n idx: number;\n version: string;\n when: number;\n tag: string;\n breakpoints: boolean;\n}\n\n/**\n * Interface for journal data\n */\ninterface JournalData {\n version: string;\n dialect: string;\n entries: JournalEntry[];\n}\n\n/**\n * Replaces MySQL types with custom types in the generated schema\n * @param schemaContent - The content of the generated schema file\n * @returns Modified schema content with custom types\n */\nfunction replaceMySQLTypes(schemaContent: string): string {\n // Add imports at the top of the file\n const imports = `import { forgeDateTimeString, forgeTimeString, forgeDateString, forgeTimestampString } from \"forge-sql-orm\";\\n\\n`;\n\n // Replace types in the content\n let modifiedContent = schemaContent\n // Handle datetime with column name and mode option\n .replace(\n /datetime\\(['\"]([^'\"]+)['\"],\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\)/g,\n \"forgeDateTimeString('$1')\",\n )\n // Handle datetime with column name only\n .replace(/datetime\\(['\"]([^'\"]+)['\"]\\)/g, \"forgeDateTimeString('$1')\")\n // Handle datetime with mode option only\n .replace(/datetime\\(\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\s*\\)/g, \"forgeDateTimeString()\")\n // Handle time with column name and mode option\n .replace(/time\\(['\"]([^'\"]+)['\"],\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\)/g, \"forgeTimeString('$1')\")\n // Handle time with column name only\n .replace(/time\\(['\"]([^'\"]+)['\"]\\)/g, \"forgeTimeString('$1')\")\n // Handle time with mode option only\n .replace(/time\\(\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\s*\\)/g, \"forgeTimeString()\")\n // Handle date with column name and mode option\n .replace(/date\\(['\"]([^'\"]+)['\"],\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\)/g, \"forgeDateString('$1')\")\n // Handle date with column name only\n .replace(/date\\(['\"]([^'\"]+)['\"]\\)/g, \"forgeDateString('$1')\")\n // Handle date with mode option only\n .replace(/date\\(\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\s*\\)/g, \"forgeDateString()\")\n // Handle timestamp with column name and mode option\n .replace(\n /timestamp\\(['\"]([^'\"]+)['\"],\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\)/g,\n \"forgeTimestampString('$1')\",\n )\n // Handle timestamp with column name only\n .replace(/timestamp\\(['\"]([^'\"]+)['\"]\\)/g, \"forgeTimestampString('$1')\")\n // Handle timestamp with mode option only\n .replace(/timestamp\\(\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\s*\\)/g, \"forgeTimestampString()\");\n\n // Add imports if they don't exist\n if (!modifiedContent.includes(\"import { forgeDateTimeString\")) {\n modifiedContent = imports + modifiedContent;\n }\n\n return modifiedContent;\n}\n\n/**\n * Generates models for all tables in the database using drizzle-kit\n * @param options - Generation options\n */\nexport const generateModels = async (options: GenerateModelsOptions) => {\n try {\n // Generate models using drizzle-kit pull\n await execSync(\n `npx drizzle-kit pull --dialect mysql --url mysql://${options.user}:${options.password}@${options.host}:${options.port}/${options.dbName} --out ${options.output}`,\n { encoding: \"utf-8\" },\n );\n\n // Process metadata to create version map\n const metaDir = path.join(options.output, \"meta\");\n const additionalMetadata: AdditionalMetadata = {};\n\n if (fs.existsSync(metaDir)) {\n const snapshotFile = path.join(metaDir, \"0000_snapshot.json\");\n if (fs.existsSync(snapshotFile)) {\n const snapshotData = JSON.parse(fs.readFileSync(snapshotFile, \"utf-8\"));\n\n // Process each table from the snapshot\n for (const [tableName, tableData] of Object.entries(snapshotData.tables)) {\n const table = tableData as TableMetadata;\n\n // Find version field in columns\n const versionField = Object.entries(table.columns).find(\n ([_, col]) => col.name.toLowerCase() === options.versionField,\n );\n\n if (versionField) {\n const [_, col] = versionField;\n const fieldType = col.type;\n const isSupportedType =\n fieldType === \"datetime\" ||\n fieldType === \"timestamp\" ||\n fieldType === \"int\" ||\n fieldType === \"number\" ||\n fieldType === \"decimal\";\n if (!col.notNull) {\n console.warn(\n `Version field \"${col.name}\" in table ${tableName} is nullable. Versioning may not work correctly.`,\n );\n } else if (!isSupportedType) {\n console.warn(\n `Version field \"${col.name}\" in table ${tableName} has unsupported type \"${fieldType}\". ` +\n `Only datetime, timestamp, int, and decimal types are supported for versioning. Versioning will be skipped.`,\n );\n } else {\n additionalMetadata[tableName] = {\n tableName,\n versionField: {\n fieldName: col.name,\n },\n };\n }\n }\n }\n }\n }\n\n // Create version metadata file\n const versionMetadataContent = `/**\n * This file was auto-generated by forge-sql-orm\n * Generated at: ${new Date().toISOString()}\n * \n * DO NOT EDIT THIS FILE MANUALLY\n * Any changes will be overwritten on next generation\n */\n \n \nexport * from \"./relations\";\nexport * from \"./schema\";\n\nexport interface VersionFieldMetadata {\n fieldName: string;\n}\n\nexport interface TableMetadata {\n tableName: string;\n versionField: VersionFieldMetadata;\n}\n\nexport type AdditionalMetadata = Record<string, TableMetadata>;\n\nexport const additionalMetadata: AdditionalMetadata = ${JSON.stringify(additionalMetadata, null, 2)};\n`;\n\n fs.writeFileSync(path.join(options.output, \"index.ts\"), versionMetadataContent);\n\n // Replace MySQL types in the generated schema file\n const schemaPath = path.join(options.output, \"schema.ts\");\n if (fs.existsSync(schemaPath)) {\n const schemaContent = fs.readFileSync(schemaPath, \"utf-8\");\n const modifiedContent = replaceMySQLTypes(schemaContent);\n fs.writeFileSync(schemaPath, modifiedContent);\n console.log(`✅ Updated schema types in: ${schemaPath}`);\n }\n\n // Remove migration files and meta directory if they exist\n const migrationDir = path.join(options.output, \"migrations\");\n\n if (fs.existsSync(migrationDir)) {\n fs.rmSync(migrationDir, { recursive: true, force: true });\n console.log(`✅ Removed: ${migrationDir}`);\n }\n\n // Read journal and remove corresponding SQL file\n if (fs.existsSync(metaDir)) {\n const journalFile = path.join(metaDir, \"_journal.json\");\n if (fs.existsSync(journalFile)) {\n const journalData = JSON.parse(fs.readFileSync(journalFile, \"utf-8\")) as JournalData;\n\n // Remove SQL files for each entry\n for (const entry of journalData.entries) {\n const sqlFile = path.join(options.output, `${entry.tag}.sql`);\n if (fs.existsSync(sqlFile)) {\n fs.rmSync(sqlFile, { force: true });\n console.log(`✅ Removed SQL file: ${entry.tag}.sql`);\n }\n }\n }\n\n // Remove meta directory after processing\n fs.rmSync(metaDir, { recursive: true, force: true });\n console.log(`✅ Removed: ${metaDir}`);\n }\n\n console.log(`✅ Successfully generated models and version metadata`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error during model generation:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\n\nimport { execSync } from \"child_process\";\n\n/**\n * Options for migration creation\n */\nexport interface CreateMigrationOptions {\n output: string;\n entitiesPath: string;\n force?: boolean;\n}\n\n/**\n * Loads the current migration version from `migrationCount.ts`.\n * @param migrationPath - Path to the migration folder.\n * @returns The latest migration version.\n */\nexport const loadMigrationVersion = async (migrationPath: string): Promise<number> => {\n try {\n const migrationCountFilePath = path.resolve(path.join(migrationPath, \"migrationCount.ts\"));\n if (!fs.existsSync(migrationCountFilePath)) {\n console.log(`✅ Current migration version: 0`);\n return 0;\n }\n\n const { MIGRATION_VERSION } = await import(migrationCountFilePath);\n console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);\n return MIGRATION_VERSION as number;\n } catch (error) {\n console.error(`❌ Error loading migrationCount:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Cleans SQL statements by removing unnecessary database options.\n * @param sql - The raw SQL statement.\n * @returns The cleaned SQL statement.\n */\nexport function cleanSQLStatement(sql: string): string {\n // Add IF NOT EXISTS to CREATE TABLE statements\n sql = sql.replace(/create\\s+table\\s+(\\w+)/gi, \"create table if not exists $1\");\n\n // Add IF NOT EXISTS to CREATE INDEX statements\n sql = sql.replace(/create\\s+index\\s+(\\w+)/gi, \"create index if not exists $1\");\n\n // Add IF NOT EXISTS to ADD INDEX statements\n sql = sql.replace(\n /alter\\s+table\\s+(\\w+)\\s+add\\s+index\\s+(\\w+)/gi,\n \"alter table $1 add index if not exists $2\",\n );\n\n // Add IF NOT EXISTS to ADD CONSTRAINT statements\n sql = sql.replace(\n /alter\\s+table\\s+(\\w+)\\s+add\\s+constraint\\s+(\\w+)/gi,\n \"alter table $1 add constraint if not exists $2\",\n );\n\n // Remove unnecessary database options\n return sql.replace(/\\s+default\\s+character\\s+set\\s+utf8mb4\\s+engine\\s*=\\s*InnoDB;?/gi, \"\").trim();\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nexport function generateMigrationFile(createStatements: string[], version: number): string {\n const versionPrefix = `v${version}_MIGRATION`;\n\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map(\n (stmt, index) =>\n ` .enqueue(\"${versionPrefix}${index}\", \"${cleanSQLStatement(stmt).replace(/\\s+/g, \" \")}\")`,\n )\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n */\nexport function saveMigrationFiles(migrationCode: string, version: number, outputDir: string) {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file with static imports\n // Build import lines for each migration version\n const importLines = [];\n for (let i = 1; i <= version; i++) {\n importLines.push(`import v${i} from \"./migrationV${i}\";`);\n }\n // Build call lines for each migration version\n const callLines = [];\n for (let i = 1; i <= version; i++) {\n callLines.push(` v${i}(migrationRunner);`);\n }\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\n${importLines.join(\"\\n\")}\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n${callLines.join(\"\\n\")}\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n}\n\n/**\n * Extracts only the relevant SQL statements for migration.\n * @param schema - The full database schema as SQL.\n * @returns Filtered list of SQL statements.\n */\nexport const extractCreateStatements = (schema: string): string[] => {\n // Split by statement-breakpoint and semicolon\n const statements = schema\n .split(/--> statement-breakpoint|;/)\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n\n return statements.filter(\n (stmt) =>\n stmt.toLowerCase().startsWith(\"create table\") ||\n stmt.toLowerCase().startsWith(\"alter table\") ||\n stmt.toLowerCase().includes(\"add index\") ||\n stmt.toLowerCase().includes(\"create index\") ||\n stmt.toLowerCase().includes(\"add unique index\") ||\n stmt.toLowerCase().includes(\"add constraint\"),\n );\n};\n\n/**\n * Creates a full database migration.\n * @param options - Database connection settings and output paths.\n */\nexport const createMigration = async (options: CreateMigrationOptions) => {\n try {\n let version = await loadMigrationVersion(options.output);\n\n if (version > 0) {\n if (options.force) {\n console.warn(\n `⚠️ Warning: Migration already exists. Creating new migration with force flag...`,\n );\n } else {\n console.error(\n `❌ Error: Migration has already been created. Use --force flag to override.`,\n );\n process.exit(1);\n }\n }\n\n // Generate SQL using drizzle-kit\n await execSync(\n `npx drizzle-kit generate --name=init --dialect mysql --out ${options.output} --schema ${options.entitiesPath}`,\n { encoding: \"utf-8\" },\n );\n const initSqlFile = path.join(options.output, \"0000_init.sql\");\n const sql = fs.readFileSync(initSqlFile, \"utf-8\");\n\n // Extract and clean statements\n const createStatements = extractCreateStatements(sql);\n\n // Generate and save migration files\n const migrationFile = generateMigrationFile(createStatements, 1);\n saveMigrationFiles(migrationFile, 1, options.output);\n\n fs.rmSync(initSqlFile, { force: true });\n console.log(`✅ Removed SQL file: ${initSqlFile}`);\n // Remove meta directory after processing\n let metaDir = path.join(options.output, \"meta\");\n fs.rmSync(metaDir, { recursive: true, force: true });\n console.log(`✅ Removed: ${metaDir}`);\n console.log(`✅ Migration successfully created!`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error during migration creation:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport mysql from \"mysql2/promise\";\nimport { MySqlTable, TableConfig } from \"drizzle-orm/mysql-core\";\nimport { RowDataPacket } from \"mysql2\";\nimport { getTableMetadata } from \"forge-sql-orm\";\nimport { AnyIndexBuilder } from \"drizzle-orm/mysql-core/indexes\";\nimport { ForeignKeyBuilder } from \"drizzle-orm/mysql-core/foreign-keys\";\nimport { UniqueConstraintBuilder } from \"drizzle-orm/mysql-core/unique-constraint\";\n\ninterface DrizzleColumn {\n type: string;\n notNull: boolean;\n autoincrement?: boolean;\n columnType?: any;\n name: string;\n getSQLType: () => string;\n}\n\ninterface DrizzleSchema {\n [tableName: string]: {\n [columnName: string]: DrizzleColumn;\n };\n}\n\ninterface DatabaseColumn extends RowDataPacket {\n TABLE_NAME: string;\n COLUMN_NAME: string;\n COLUMN_TYPE: string;\n IS_NULLABLE: string;\n COLUMN_KEY: string;\n EXTRA: string;\n}\n\ninterface DatabaseIndex extends RowDataPacket {\n TABLE_NAME: string;\n INDEX_NAME: string;\n COLUMN_NAME: string;\n NON_UNIQUE: number;\n}\n\ninterface DatabaseForeignKey extends RowDataPacket {\n TABLE_NAME: string;\n COLUMN_NAME: string;\n CONSTRAINT_NAME: string;\n REFERENCED_TABLE_NAME: string;\n REFERENCED_COLUMN_NAME: string;\n}\n\ninterface TableSchema {\n columns: Record<string, DatabaseColumn>;\n indexes: Record<\n string,\n {\n columns: string[];\n unique: boolean;\n }\n >;\n foreignKeys: Record<\n string,\n {\n column: string;\n referencedTable: string;\n referencedColumn: string;\n }\n >;\n}\n\ninterface DatabaseSchema {\n [tableName: string]: TableSchema;\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nfunction generateMigrationFile(createStatements: string[], version: number): string {\n const versionPrefix = `v${version}_MIGRATION`;\n\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map((stmt, index) => ` .enqueue(\"${versionPrefix}${index}\", \"${stmt}\")`)\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Filters out SQL statements that already exist in the previous migration file\n * @param newStatements - Array of SQL statements from new migration\n * @param prevVersion - Previous migration version\n * @param outputDir - Directory where migration files are stored\n * @returns Array of SQL statements that don't exist in previous migration\n */\nfunction filterWithPreviousMigration(\n newStatements: string[],\n prevVersion: number,\n outputDir: string,\n): string[] {\n const prevMigrationPath = path.join(outputDir, `migrationV${prevVersion}.ts`);\n\n if (!fs.existsSync(prevMigrationPath)) {\n return newStatements.map((s) => s.replace(/\\s+/g, \" \"));\n }\n\n // Read previous migration file\n const prevContent = fs.readFileSync(prevMigrationPath, \"utf-8\");\n\n // Extract SQL statements from the file\n const prevStatements = prevContent\n .split(\"\\n\")\n .filter((line) => line.includes(\".enqueue(\"))\n .map((line) => {\n const match = line.match(/\\.enqueue\\([^,]+,\\s*\"([^\"]+)\"/);\n return match ? match[1].replace(/\\s+/g, \" \").trim() : \"\";\n });\n\n // Filter out statements that already exist in previous migration\n return newStatements\n .filter((s) => !prevStatements.includes(s.replace(/\\s+/g, \" \")))\n .map((s) => s.replace(/\\s+/g, \" \"));\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n * @returns boolean indicating if migration was saved\n */\nfunction saveMigrationFiles(migrationCode: string, version: number, outputDir: string): boolean {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\nimport { MIGRATION_VERSION } from \"./migrationCount\";\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n for (let i = 1; i <= MIGRATION_VERSION; i++) {\n const migrations = (await import(\\`./migrationV\\${i}\\`)) as {\n default: MigrationType;\n };\n migrations.default(migrationRunner);\n }\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n\n return true;\n}\n\n/**\n * Loads the current migration version from `migrationCount.ts`.\n * @param migrationPath - Path to the migration folder.\n * @returns The latest migration version.\n */\nconst loadMigrationVersion = async (migrationPath: string): Promise<number> => {\n try {\n const migrationCountFilePath = path.resolve(path.join(migrationPath, \"migrationCount.ts\"));\n if (!fs.existsSync(migrationCountFilePath)) {\n console.warn(\n `⚠️ Warning: migrationCount.ts not found in ${migrationCountFilePath}, assuming no previous migrations.`,\n );\n return 0;\n }\n\n const { MIGRATION_VERSION } = await import(migrationCountFilePath);\n console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);\n return MIGRATION_VERSION as number;\n } catch (error) {\n console.error(`❌ Error loading migrationCount:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Gets the current database schema from MySQL including indexes and foreign keys\n * @param connection - MySQL connection\n * @param dbName - Database name\n * @returns Database schema object with indexes and foreign keys\n */\nasync function getDatabaseSchema(\n connection: mysql.Connection,\n dbName: string,\n): Promise<DatabaseSchema> {\n // Get columns\n const [columns] = await connection.execute<DatabaseColumn[]>(\n `\n SELECT TABLE_NAME, COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY, EXTRA\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_SCHEMA = ?\n `,\n [dbName],\n );\n\n // Get indexes\n const [indexes] = await connection.execute<DatabaseIndex[]>(\n `\n SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, NON_UNIQUE\n FROM INFORMATION_SCHEMA.STATISTICS\n WHERE TABLE_SCHEMA = ?\n ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX\n `,\n [dbName],\n );\n\n // Get foreign keys\n const [foreignKeys] = await connection.execute<DatabaseForeignKey[]>(\n `\n SELECT \n TABLE_NAME,\n COLUMN_NAME,\n CONSTRAINT_NAME,\n REFERENCED_TABLE_NAME,\n REFERENCED_COLUMN_NAME\n FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE\n WHERE TABLE_SCHEMA = ?\n AND REFERENCED_TABLE_NAME IS NOT NULL\n `,\n [dbName],\n );\n\n const schema: DatabaseSchema = {};\n\n // Process columns\n columns.forEach((row) => {\n if (!schema[row.TABLE_NAME]) {\n schema[row.TABLE_NAME] = {\n columns: {},\n indexes: {},\n foreignKeys: {},\n };\n }\n schema[row.TABLE_NAME].columns[row.COLUMN_NAME] = row;\n });\n\n // Process indexes\n indexes.forEach((row) => {\n if (!schema[row.TABLE_NAME].indexes[row.INDEX_NAME]) {\n schema[row.TABLE_NAME].indexes[row.INDEX_NAME] = {\n columns: [],\n unique: !row.NON_UNIQUE,\n };\n }\n schema[row.TABLE_NAME].indexes[row.INDEX_NAME].columns.push(row.COLUMN_NAME);\n });\n\n // Process foreign keys\n foreignKeys.forEach((row) => {\n if (!schema[row.TABLE_NAME].foreignKeys[row.CONSTRAINT_NAME]) {\n schema[row.TABLE_NAME].foreignKeys[row.CONSTRAINT_NAME] = {\n column: row.COLUMN_NAME,\n referencedTable: row.REFERENCED_TABLE_NAME,\n referencedColumn: row.REFERENCED_COLUMN_NAME,\n };\n }\n });\n\n return schema;\n}\n\n/**\n * Converts MySQL type to normalized format for comparison\n * @param mysqlType - MySQL type from INFORMATION_SCHEMA or Drizzle type\n * @returns Normalized type string\n */\nfunction normalizeMySQLType(mysqlType: string): string {\n // Remove length/precision information\n let normalized = mysqlType.replace(/\\([^)]*\\)/, \"\").toLowerCase();\n\n // Remove 'mysql' prefix from Drizzle types\n normalized = normalized.replace(/^mysql/, \"\");\n\n return normalized;\n}\n\n/**\n * Gets the name of a foreign key constraint\n * @param fk - The foreign key builder\n * @returns The name of the foreign key constraint\n */\nfunction getForeignKeyName(fk: ForeignKeyBuilder): string {\n // @ts-ignore - Internal property access\n return fk.name;\n}\n\n/**\n * Gets the name of an index\n * @param index - The index builder\n * @returns The name of the index\n */\nfunction getIndexName(index: AnyIndexBuilder): string {\n // @ts-ignore - Internal property access\n return index.name;\n}\n\n/**\n * Gets the name of a unique constraint\n * @param uc - The unique constraint builder\n * @returns The name of the unique constraint\n */\nfunction getUniqueConstraintName(uc: UniqueConstraintBuilder): string {\n // @ts-ignore - Internal property access\n return uc.name;\n}\n\n/**\n * Gets the columns of an index\n * @param index - The index builder\n * @returns Array of column names\n */\nfunction getIndexColumns(index: AnyIndexBuilder): string[] {\n // @ts-ignore - Internal property access\n return index.columns.map((col) => col.name);\n}\n\nfunction compareForeignKey(\n fk: ForeignKeyBuilder,\n { columns }: { columns: string[]; unique: boolean },\n) {\n // @ts-ignore\n const fcolumns: string[] = fk.columns.map((c) => c.name);\n return fcolumns.sort().join(\",\") === columns.sort().join(\",\");\n}\n\n/**\n * Generates SQL changes by comparing Drizzle schema with database schema\n * @param drizzleSchema - Schema from Drizzle\n * @param dbSchema - Schema from database\n * @param schemaModule - Drizzle schema module\n * @returns Array of SQL statements\n */\nfunction generateSchemaChanges(\n drizzleSchema: DrizzleSchema,\n dbSchema: DatabaseSchema,\n schemaModule: Record<string, any>,\n): string[] {\n const changes: string[] = [];\n\n // First check existing tables in database\n for (const [tableName, dbTable] of Object.entries(dbSchema)) {\n const drizzleColumns = drizzleSchema[tableName];\n\n if (!drizzleColumns) {\n // Table exists in database but not in schema - create it\n const columns = Object.entries(dbTable.columns)\n .map(([colName, col]) => {\n const type = col.COLUMN_TYPE;\n const nullable = col.IS_NULLABLE === \"YES\" ? \"NULL\" : \"NOT NULL\";\n const autoIncrement = col.EXTRA.includes(\"auto_increment\") ? \"AUTO_INCREMENT\" : \"\";\n return `\\`${colName}\\` ${type} ${nullable} ${autoIncrement}`.trim();\n })\n .join(\",\\n \");\n\n changes.push(`CREATE TABLE if not exists \\`${tableName}\\` (\\n ${columns}\\n);`);\n\n // Create indexes for new table\n for (const [indexName, dbIndex] of Object.entries(dbTable.indexes)) {\n // Skip primary key and foreign key indexes\n if (indexName === \"PRIMARY\") {\n continue;\n }\n\n // Check if any column in this index is a foreign key\n const isForeignKeyIndex = dbIndex.columns.some((colName) => {\n const column = dbTable.columns[colName];\n return column && column.COLUMN_KEY === \"MUL\" && column.EXTRA.includes(\"foreign key\");\n });\n\n if (isForeignKeyIndex) {\n continue;\n }\n\n // Create index\n const columns = dbIndex.columns.map((col) => `\\`${col}\\``).join(\", \");\n const unique = dbIndex.unique ? \"UNIQUE \" : \"\";\n changes.push(\n `CREATE ${unique}INDEX if not exists \\`${indexName}\\` ON \\`${tableName}\\` (${columns});`,\n );\n }\n\n // Create foreign keys for new table\n for (const [fkName, dbFK] of Object.entries(dbTable.foreignKeys)) {\n changes.push(\n `ALTER TABLE \\`${tableName}\\` ADD CONSTRAINT \\`${fkName}\\` FOREIGN KEY (\\`${dbFK.column}\\`) REFERENCES \\`${dbFK.referencedTable}\\` (\\`${dbFK.referencedColumn}\\`);`,\n );\n }\n continue;\n }\n\n // Check for column changes in existing tables\n for (const [colName, dbCol] of Object.entries(dbTable.columns)) {\n const drizzleCol = Object.values(drizzleColumns).find((c) => c.name === colName);\n\n if (!drizzleCol) {\n // Column exists in database but not in schema - create it\n const type = dbCol.COLUMN_TYPE;\n const nullable = dbCol.IS_NULLABLE === \"YES\" ? \"NULL\" : \"NOT NULL\";\n changes.push(`ALTER TABLE \\`${tableName}\\` ADD COLUMN IF NOT EXISTS \\`${colName}\\` ${type} ${nullable};`);\n continue;\n }\n\n // Check for type changes\n const normalizedDbType = normalizeMySQLType(dbCol.COLUMN_TYPE);\n const normalizedDrizzleType = normalizeMySQLType(drizzleCol.getSQLType());\n\n if (normalizedDbType !== normalizedDrizzleType) {\n const type = dbCol.COLUMN_TYPE; // Use database type as source of truth\n const nullable = dbCol.IS_NULLABLE === \"YES\" ? \"NULL\" : \"NOT NULL\";\n changes.push(\n `ALTER TABLE \\`${tableName}\\` MODIFY COLUMN \\`${colName}\\` IF EXISTS ${type} ${nullable};`,\n );\n }\n }\n\n // Check for index changes\n const table = Object.values(schemaModule).find((t) => {\n const metadata = getTableMetadata(t);\n return metadata.tableName === tableName;\n });\n\n if (table) {\n const metadata = getTableMetadata(table);\n // First check indexes that exist in database but not in schema\n for (const [indexName, dbIndex] of Object.entries(dbTable.indexes)) {\n // Skip primary key and foreign key indexes\n if (indexName === \"PRIMARY\") {\n continue;\n }\n\n // Check if this is a foreign key index\n const isForeignKeyIndex = metadata.foreignKeys.some(\n (fk) => getForeignKeyName(fk) === indexName || compareForeignKey(fk, dbIndex),\n );\n if (isForeignKeyIndex) {\n continue;\n }\n\n // Check if this is a unique constraint\n const existsUniqIndex = metadata.uniqueConstraints.find(\n (uc) => getUniqueConstraintName(uc) === indexName,\n );\n let drizzleIndex = metadata.indexes.find((i) => getIndexName(i) === indexName);\n\n if (!drizzleIndex && existsUniqIndex) {\n drizzleIndex = existsUniqIndex as unknown as AnyIndexBuilder;\n }\n\n if (!drizzleIndex) {\n // Index exists in database but not in schema - create it\n const columns = dbIndex.columns.map((col) => `\\`${col}\\``).join(\", \");\n const unique = dbIndex.unique ? \"UNIQUE \" : \"\";\n changes.push(\n `CREATE ${unique}INDEX if not exists \\`${indexName}\\` ON \\`${tableName}\\` (${columns});`,\n );\n continue;\n }\n\n // Check if index columns changed\n const dbColumns = dbIndex.columns.join(\", \");\n const drizzleColumns = getIndexColumns(drizzleIndex).join(\", \");\n if (\n dbColumns !== drizzleColumns ||\n dbIndex.unique !== drizzleIndex instanceof UniqueConstraintBuilder\n ) {\n // Drop and recreate index using database values\n changes.push(`DROP INDEX \\`${indexName}\\` ON \\`${tableName}\\`;`);\n const columns = dbIndex.columns.map((col) => `\\`${col}\\``).join(\", \");\n const unique = dbIndex.unique ? \"UNIQUE \" : \"\";\n changes.push(\n `CREATE ${unique}INDEX if not exists \\`${indexName}\\` ON \\`${tableName}\\` (${columns});`,\n );\n }\n }\n\n // First check foreign keys that exist in database but not in schema\n for (const [fkName, dbFK] of Object.entries(dbTable.foreignKeys)) {\n // Find if this column is referenced in Drizzle schema\n const drizzleFK = metadata.foreignKeys.find(\n (fk) =>\n getForeignKeyName(fk) === fkName ||\n compareForeignKey(fk, { columns: [dbFK.column], unique: false }),\n );\n\n if (!drizzleFK) {\n // Foreign key exists in database but not in schema - drop it\n changes.push(\n `ALTER TABLE \\`${tableName}\\` ADD CONSTRAINT \\`${fkName}\\` FOREIGN KEY (\\`${dbFK.column}\\`) REFERENCES \\`${dbFK.referencedTable}\\` (\\`${dbFK.referencedColumn}\\`);`,\n );\n continue;\n }\n }\n\n // Then check for new foreign keys that exist in schema but not in database\n for (const drizzleForeignKey of metadata.foreignKeys) {\n // Find if this foreign key exists in database\n const isDbFk = Object.keys(dbTable.foreignKeys).find((fk) => {\n let foreignKey = dbTable.foreignKeys[fk];\n return (\n fk === getForeignKeyName(drizzleForeignKey) ||\n compareForeignKey(drizzleForeignKey, { columns: [foreignKey.column], unique: false })\n );\n });\n\n if (!isDbFk) {\n // Foreign key exists in schema but not in database - create it\n if (drizzleForeignKey) {\n const fkName = getForeignKeyName(drizzleForeignKey);\n if (fkName) {\n changes.push(`ALTER TABLE \\`${tableName}\\` DROP FOREIGN KEY \\`${fkName}\\`;`);\n } else {\n // @ts-ignore\n const columns = drizzleForeignKey.columns;\n const columnNames = columns?.length\n ? columns.map((c: any) => c.name).join(\", \")\n : \"unknown columns\";\n console.warn(\n `⚠️ Drizzle model for table '${tableName}' does not provide a name for FOREIGN KEY constraint on columns: ${columnNames}`,\n );\n }\n }\n }\n }\n }\n }\n\n return changes;\n}\n\n/**\n * Updates an existing database migration by generating schema modifications.\n * @param options - Database connection settings and output paths.\n */\nexport const updateMigration = async (options: any) => {\n try {\n let version = await loadMigrationVersion(options.output);\n const prevVersion = version;\n\n if (version < 1) {\n console.log(\n `⚠️ Initial migration not found. Run \"npx forge-sql-orm migrations:create\" first.`,\n );\n process.exit(0);\n }\n version += 1;\n\n // Create database connection\n const connection = await mysql.createConnection({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n database: options.dbName,\n });\n\n try {\n // Get current database schema\n const dbSchema = await getDatabaseSchema(connection, options.dbName);\n\n // Import Drizzle schema using absolute path\n const schemaPath = path.resolve(options.entitiesPath, \"schema.ts\");\n if (!fs.existsSync(schemaPath)) {\n throw new Error(`Schema file not found at: ${schemaPath}`);\n }\n\n const schemaModule = await import(schemaPath);\n if (!schemaModule) {\n throw new Error(`Invalid schema file at: ${schemaPath}. Schema must export tables.`);\n }\n\n // Process exported tables\n const drizzleSchema: DrizzleSchema = {};\n\n // Get all exports that are tables\n const tables = Object.values(schemaModule) as MySqlTable<TableConfig>[];\n\n tables.forEach((table) => {\n const metadata = getTableMetadata(table);\n if (metadata.tableName) {\n // Convert AnyColumn to DrizzleColumn\n const columns: Record<string, DrizzleColumn> = {};\n Object.entries(metadata.columns).forEach(([name, column]) => {\n columns[name] = {\n type: column.dataType,\n notNull: column.notNull,\n autoincrement: (column as any).autoincrement,\n columnType: column.columnType,\n name: column.name,\n getSQLType: () => column.getSQLType(),\n };\n });\n drizzleSchema[metadata.tableName] = columns;\n }\n });\n\n if (Object.keys(drizzleSchema).length === 0) {\n throw new Error(`No valid tables found in schema at: ${schemaPath}`);\n }\n\n console.log(\"Found tables:\", Object.keys(drizzleSchema));\n\n // Generate SQL changes\n const createStatements = filterWithPreviousMigration(\n generateSchemaChanges(drizzleSchema, dbSchema, schemaModule),\n prevVersion,\n options.output,\n );\n\n if (createStatements.length) {\n // Generate migration file content\n const migrationFile = generateMigrationFile(createStatements, version);\n\n // Save migration files only if there are actual changes\n if (saveMigrationFiles(migrationFile, version, options.output)) {\n console.log(`✅ Migration successfully updated!`);\n }\n process.exit(0);\n } else {\n console.log(`⚠️ No new migration changes detected.`);\n process.exit(0);\n }\n } finally {\n await connection.end();\n }\n } catch (error) {\n console.error(`❌ Error during migration update:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { MySqlTable, TableConfig } from \"drizzle-orm/mysql-core\";\nimport { getTableMetadata, generateDropTableStatements } from \"forge-sql-orm\";\n\n/**\n * Generates a migration ID using current date\n * @returns Migration ID string with current date\n */\nfunction generateMigrationUUID(version: number): string {\n const now = new Date();\n const timestamp = now.getTime();\n return `MIGRATION_V${version}_${timestamp}`;\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nfunction generateMigrationFile(createStatements: string[], version: number): string {\n const uniqId = generateMigrationUUID(version);\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map(\n (stmt, index) => ` .enqueue(\"${uniqId}_${index}\", \\\"${stmt}\\\")`, // eslint-disable-line no-useless-escape\n )\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n */\nfunction saveMigrationFiles(migrationCode: string, version: number, outputDir: string) {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\nimport { MIGRATION_VERSION } from \"./migrationCount\";\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n for (let i = 1; i <= MIGRATION_VERSION; i++) {\n const migrations = (await import(\\`./migrationV\\${i}\\`)) as {\n default: MigrationType;\n };\n migrations.default(migrationRunner);\n }\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n}\n\n/**\n * Creates a full database migration.\n * @param options - Database connection settings and output paths.\n */\nexport const dropMigration = async (options: any) => {\n try {\n // Start from version 1 if no previous migrations exist\n const version = 1;\n\n // Import Drizzle schema using absolute path\n const schemaPath = path.resolve(options.entitiesPath, \"schema.ts\");\n if (!fs.existsSync(schemaPath)) {\n throw new Error(`Schema file not found at: ${schemaPath}`);\n }\n\n const schemaModule = await import(schemaPath);\n if (!schemaModule) {\n throw new Error(`Invalid schema file at: ${schemaPath}. Schema must export tables.`);\n }\n\n // Get all exports that are tables\n const tables = Object.values(schemaModule) as MySqlTable<TableConfig>[];\n\n if (tables.length === 0) {\n throw new Error(`No valid tables found in schema at: ${schemaPath}`);\n }\n\n // Get table names for logging\n const tableNames = tables\n .map((table) => {\n const metadata = getTableMetadata(table);\n return metadata.tableName;\n })\n .filter(Boolean);\n\n console.log(\"Found tables:\", tableNames);\n\n // Generate drop statements\n const dropStatements = generateDropTableStatements(tableNames);\n\n // Generate and save migration files\n const migrationFile = generateMigrationFile(dropStatements, version);\n saveMigrationFiles(migrationFile, version, options.output);\n\n console.log(`✅ Migration successfully created!`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error during migration creation:`, error);\n process.exit(1);\n }\n};\n","#!/usr/bin/env node\n\nimport { Command } from \"commander\";\nimport dotenv from \"dotenv\";\nimport inquirer from \"inquirer\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { generateModels } from \"./actions/generate-models\";\nimport { createMigration } from \"./actions/migrations-create\";\nimport { updateMigration } from \"./actions/migrations-update\";\nimport { dropMigration } from \"./actions/migrations-drops\";\n\nconst ENV_PATH = path.resolve(process.cwd(), \".env\");\n// 🔄 Load environment variables from `.env` file\ndotenv.config({ path: ENV_PATH });\n\nconst saveEnvFile = (config: any) => {\n let envContent = \"\";\n const envFilePath = ENV_PATH;\n\n if (fs.existsSync(envFilePath)) {\n envContent = fs.readFileSync(envFilePath, \"utf8\");\n }\n\n const envVars = envContent\n .split(\"\\n\")\n .filter((line) => line.trim() !== \"\" && !line.startsWith(\"#\"))\n .reduce((acc: any, line) => {\n const [key, ...value] = line.split(\"=\");\n acc[key] = value.join(\"=\");\n return acc;\n }, {});\n\n Object.entries(config).forEach(([key, value]) => {\n envVars[`FORGE_SQL_ORM_${key.toUpperCase()}`] = value;\n });\n\n const updatedEnvContent = Object.entries(envVars)\n .map(([key, value]) => `${key}=${value}`)\n .join(\"\\n\");\n\n fs.writeFileSync(envFilePath, updatedEnvContent, { encoding: \"utf8\" });\n\n console.log(\"✅ Configuration saved to .env without overwriting other variables.\");\n};\n\n/**\n * Prompts the user for missing parameters using Inquirer.js.\n * @param config - The current configuration object.\n * @param defaultOutput - Default output path.\n * @param customAskMissingParams - Optional function for additional prompts.\n * @returns Updated configuration with user input.\n */\nconst askMissingParams = async (\n config: any,\n defaultOutput: string,\n customAskMissingParams?: (cfg: any, questions: unknown[]) => void,\n) => {\n const questions: unknown[] = [];\n\n if (!config.host)\n questions.push({\n type: \"input\",\n name: \"host\",\n message: \"Enter database host:\",\n default: \"localhost\",\n });\n\n if (!config.port)\n questions.push({\n type: \"input\",\n name: \"port\",\n message: \"Enter database port:\",\n default: \"3306\",\n validate: (input: string) => !isNaN(parseInt(input, 10)),\n });\n\n if (!config.user)\n questions.push({\n type: \"input\",\n name: \"user\",\n message: \"Enter database user:\",\n default: \"root\",\n });\n\n if (!config.password)\n questions.push({\n type: \"password\",\n name: \"password\",\n message: \"Enter database password:\",\n mask: \"*\",\n });\n\n if (!config.dbName)\n questions.push({\n type: \"input\",\n name: \"dbName\",\n message: \"Enter database name:\",\n });\n\n if (!config.output)\n questions.push({\n type: \"input\",\n name: \"output\",\n message: \"Enter output path:\",\n default: defaultOutput,\n });\n\n // Allow additional questions from the caller\n if (customAskMissingParams) {\n customAskMissingParams(config, questions);\n }\n\n // If there are missing parameters, prompt the user\n if (questions.length > 0) {\n // @ts-ignore - Ignore TypeScript warning for dynamic question type\n const answers = await inquirer.prompt(questions);\n return { ...config, ...answers, port: parseInt(config.port ?? answers.port, 10) };\n }\n\n return config;\n};\n\n/**\n * Retrieves configuration parameters from command-line arguments and environment variables.\n * If any required parameters are missing, prompts the user for input.\n * @param cmd - The command object containing CLI options.\n * @param defaultOutput - Default output directory.\n * @param customConfig - Optional function for additional configuration parameters.\n * @param customAskMissingParams - Optional function for additional prompts.\n * @returns A fully resolved configuration object.\n */\nconst getConfig = async (\n cmd: any,\n defaultOutput: string,\n customConfig?: () => any,\n customAskMissingParams?: (cfg: any, questions: unknown[]) => void,\n) => {\n let config = {\n host: cmd.host || process.env.FORGE_SQL_ORM_HOST,\n port: cmd.port\n ? parseInt(cmd.port, 10)\n : process.env.FORGE_SQL_ORM_PORT\n ? parseInt(process.env.FORGE_SQL_ORM_PORT, 10)\n : undefined,\n user: cmd.user || process.env.FORGE_SQL_ORM_USER,\n password: cmd.password || process.env.FORGE_SQL_ORM_PASSWORD,\n dbName: cmd.dbName || process.env.FORGE_SQL_ORM_DBNAME,\n output: cmd.output || process.env.FORGE_SQL_ORM_OUTPUT,\n };\n\n // Merge additional configurations if provided\n if (customConfig) {\n config = { ...config, ...customConfig() };\n }\n\n const conf = await askMissingParams(config, defaultOutput, customAskMissingParams);\n if (cmd.saveEnv) {\n saveEnvFile(conf);\n }\n return conf;\n};\n\n// 📌 Initialize CLI\nexport const program = new Command();\nprogram.version(\"1.0.0\");\n\n// ✅ Command: Generate database models (Entities)\nprogram\n .command(\"generate:model\")\n .description(\"Generate Drizzle models from the database.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for entities\")\n .option(\"--versionField <string>\", \"Field name for versioning\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/entities\",\n () => ({\n versionField: cmd.versionField || process.env.FORGE_SQL_ORM_VERSIONFIELD,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.versionField) {\n questions.push({\n type: \"input\",\n name: \"versionField\",\n message: \"Enter the field name for versioning (leave empty to skip):\",\n default: \"\",\n });\n }\n },\n );\n await generateModels(config);\n });\n\n// ✅ Command: Create initial database migration\nprogram\n .command(\"migrations:create\")\n .description(\"Generate an initial migration for the entire database.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--force\", \"Force creation even if migrations exist\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n force: cmd.force || false,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await createMigration(config);\n });\n\n// ✅ Command: Update migration for schema changes\nprogram\n .command(\"migrations:update\")\n .description(\"Generate a migration to update the database schema.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await updateMigration(config);\n });\n\n// ✅ Command: Drop all migrations\nprogram\n .command(\"migrations:drop\")\n .description(\"Generate a migration to drop all tables and clear migrations history.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await dropMigration(config);\n });\n\n// 🔥 Execute CLI\n program.parse(process.argv);\n"],"names":["loadMigrationVersion","generateMigrationFile","saveMigrationFiles","columns","drizzleColumns"],"mappings":";;;;;;;;;;;AAuFA,SAAS,kBAAkB,eAA+B;AAExD,QAAM,UAAU;AAAA;AAAA;AAGhB,MAAI,kBAAkB,cAEnB;AAAA,IACC;AAAA,IACA;AAAA,EAAA,EAGD,QAAQ,iCAAiC,2BAA2B,EAEpE,QAAQ,qDAAqD,uBAAuB,EAEpF,QAAQ,+DAA+D,uBAAuB,EAE9F,QAAQ,6BAA6B,uBAAuB,EAE5D,QAAQ,iDAAiD,mBAAmB,EAE5E,QAAQ,+DAA+D,uBAAuB,EAE9F,QAAQ,6B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mBAAmB,eAAe,EACzC,OAAO,mBAAmB,eAAe,EACzC,OAAO,uBAAuB,mBAAmB,EACjD,OAAO,qBAAqB,eAAe,EAC3C,OAAO,qBAAqB,4BAA4B,EACxD,OAAO,2BAA2B,wCAAwC,EAC1E,OAAO,aAAa,iCAAiC,EACrD,OAAO,OAAO,QAAQ;AACrB,QAAM,SAAS,MAAM;AAAA,IACnB;AAAA,IACA;AAAA,IACA,OAAO;AAAA,MACL,cAAc,IAAI,gBAAgB,QAAQ,IAAI;AAAA,IAAA;AAAA,IAEhD,CAAC,KAAK,cAAyB;AAC7B,UAAI,CAAC,IAAI;AACP,kBAAU,KAAK;AAAA,UACb,MAAM;AAAA,UACN,MAAM;AAAA,UACN,SAAS;AAAA,UACT,SAAS;AAAA,QAAA,CACV;AAAA,IACL;AAAA,EAAA;AAEF,QAAM,cAAc,MAAM;AAC5B,CAAC;AAGD,QAAQ,MAAM,QAAQ,IAAI;"}
|
|
1
|
+
{"version":3,"file":"cli.mjs","sources":["../src/actions/generate-models.ts","../src/actions/migrations-create.ts","../src/actions/migrations-update.ts","../src/actions/migrations-drops.ts","../src/cli.ts"],"sourcesContent":["import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { execSync } from \"child_process\";\n\n/**\n * Options for model generation\n */\ninterface GenerateModelsOptions {\n host: string;\n port: number;\n user: string;\n password: string;\n dbName: string;\n output: string;\n versionField: string;\n}\n\n/**\n * Interface for column metadata\n */\ninterface ColumnMetadata {\n autoincrement: boolean;\n name: string;\n type: string;\n primaryKey: boolean;\n notNull: boolean;\n}\n\n/**\n * Interface for table metadata\n */\ninterface TableMetadata {\n name: string;\n columns: Record<string, ColumnMetadata>;\n compositePrimaryKeys: Record<string, { name: string; columns: string[] }>;\n indexes: Record<string, any>;\n foreignKeys: Record<string, any>;\n uniqueConstraints: Record<string, any>;\n checkConstraint: Record<string, any>;\n}\n\n/**\n * Interface for version field metadata\n */\ninterface VersionFieldMetadata {\n fieldName: string;\n}\n\n/**\n * Interface for table version metadata\n */\ninterface TableVersionMetadata {\n tableName: string;\n versionField: VersionFieldMetadata;\n}\n\n/**\n * Type for additional metadata map\n */\ntype AdditionalMetadata = Record<string, TableVersionMetadata>;\n\n/**\n * Interface for journal entry\n */\ninterface JournalEntry {\n idx: number;\n version: string;\n when: number;\n tag: string;\n breakpoints: boolean;\n}\n\n/**\n * Interface for journal data\n */\ninterface JournalData {\n version: string;\n dialect: string;\n entries: JournalEntry[];\n}\n\n/**\n * Replaces MySQL types with custom types in the generated schema\n * @param schemaContent - The content of the generated schema file\n * @returns Modified schema content with custom types\n */\nfunction replaceMySQLTypes(schemaContent: string): string {\n // Add imports at the top of the file\n const imports = `import { forgeDateTimeString, forgeTimeString, forgeDateString, forgeTimestampString } from \"forge-sql-orm\";\\n\\n`;\n\n // Replace types in the content\n let modifiedContent = schemaContent\n // Handle datetime with column name and mode option\n .replace(\n /datetime\\(['\"]([^'\"]+)['\"],\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\)/g,\n \"forgeDateTimeString('$1')\",\n )\n // Handle datetime with column name only\n .replace(/datetime\\(['\"]([^'\"]+)['\"]\\)/g, \"forgeDateTimeString('$1')\")\n // Handle datetime with mode option only\n .replace(/datetime\\(\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\s*\\)/g, \"forgeDateTimeString()\")\n // Handle time with column name and mode option\n .replace(/time\\(['\"]([^'\"]+)['\"],\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\)/g, \"forgeTimeString('$1')\")\n // Handle time with column name only\n .replace(/time\\(['\"]([^'\"]+)['\"]\\)/g, \"forgeTimeString('$1')\")\n // Handle time with mode option only\n .replace(/time\\(\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\s*\\)/g, \"forgeTimeString()\")\n // Handle date with column name and mode option\n .replace(/date\\(['\"]([^'\"]+)['\"],\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\)/g, \"forgeDateString('$1')\")\n // Handle date with column name only\n .replace(/date\\(['\"]([^'\"]+)['\"]\\)/g, \"forgeDateString('$1')\")\n // Handle date with mode option only\n .replace(/date\\(\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\s*\\)/g, \"forgeDateString()\")\n // Handle timestamp with column name and mode option\n .replace(\n /timestamp\\(['\"]([^'\"]+)['\"],\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\)/g,\n \"forgeTimestampString('$1')\",\n )\n // Handle timestamp with column name only\n .replace(/timestamp\\(['\"]([^'\"]+)['\"]\\)/g, \"forgeTimestampString('$1')\")\n // Handle timestamp with mode option only\n .replace(/timestamp\\(\\s*{\\s*mode:\\s*['\"]string['\"]\\s*}\\s*\\)/g, \"forgeTimestampString()\");\n\n // Add imports if they don't exist\n if (!modifiedContent.includes(\"import { forgeDateTimeString\")) {\n modifiedContent = imports + modifiedContent;\n }\n\n return modifiedContent;\n}\n\n/**\n * Generates models for all tables in the database using drizzle-kit\n * @param options - Generation options\n */\nexport const generateModels = async (options: GenerateModelsOptions) => {\n try {\n // Generate models using drizzle-kit pull\n await execSync(\n `npx drizzle-kit pull --dialect mysql --url mysql://${options.user}:${options.password}@${options.host}:${options.port}/${options.dbName} --out ${options.output}`,\n { encoding: \"utf-8\" },\n );\n\n // Process metadata to create version map\n const metaDir = path.join(options.output, \"meta\");\n const additionalMetadata: AdditionalMetadata = {};\n\n if (fs.existsSync(metaDir)) {\n const snapshotFile = path.join(metaDir, \"0000_snapshot.json\");\n if (fs.existsSync(snapshotFile)) {\n const snapshotData = JSON.parse(fs.readFileSync(snapshotFile, \"utf-8\"));\n\n // Process each table from the snapshot\n for (const [tableName, tableData] of Object.entries(snapshotData.tables)) {\n const table = tableData as TableMetadata;\n\n // Check if table name starts with 'a_' and warn about cache\n if (tableName.toLowerCase().startsWith(\"a_\")) {\n console.warn(\n `⚠️ Table \"${tableName}\" starts with \"a_\". KVS Cache will not work with this table because such tables are ignored in cache operations.`,\n );\n }\n\n // Find version field in columns\n const versionField = Object.entries(table.columns).find(\n ([_, col]) => col.name.toLowerCase() === options.versionField,\n );\n\n if (versionField) {\n const [_, col] = versionField;\n const fieldType = col.type;\n const isSupportedType =\n fieldType === \"datetime\" ||\n fieldType === \"timestamp\" ||\n fieldType === \"int\" ||\n fieldType === \"number\" ||\n fieldType === \"decimal\";\n if (!col.notNull) {\n console.warn(\n `Version field \"${col.name}\" in table ${tableName} is nullable. Versioning may not work correctly.`,\n );\n } else if (!isSupportedType) {\n console.warn(\n `Version field \"${col.name}\" in table ${tableName} has unsupported type \"${fieldType}\". ` +\n `Only datetime, timestamp, int, and decimal types are supported for versioning. Versioning will be skipped.`,\n );\n } else {\n additionalMetadata[tableName] = {\n tableName,\n versionField: {\n fieldName: col.name,\n },\n };\n }\n }\n }\n }\n }\n\n // Create version metadata file\n const versionMetadataContent = `/**\n * This file was auto-generated by forge-sql-orm\n * Generated at: ${new Date().toISOString()}\n * \n * DO NOT EDIT THIS FILE MANUALLY\n * Any changes will be overwritten on next generation\n */\n \n \nexport * from \"./relations\";\nexport * from \"./schema\";\n\nexport interface VersionFieldMetadata {\n fieldName: string;\n}\n\nexport interface TableMetadata {\n tableName: string;\n versionField: VersionFieldMetadata;\n}\n\nexport type AdditionalMetadata = Record<string, TableMetadata>;\n\nexport const additionalMetadata: AdditionalMetadata = ${JSON.stringify(additionalMetadata, null, 2)};\n`;\n\n fs.writeFileSync(path.join(options.output, \"index.ts\"), versionMetadataContent);\n\n // Replace MySQL types in the generated schema file\n const schemaPath = path.join(options.output, \"schema.ts\");\n if (fs.existsSync(schemaPath)) {\n const schemaContent = fs.readFileSync(schemaPath, \"utf-8\");\n const modifiedContent = replaceMySQLTypes(schemaContent);\n fs.writeFileSync(schemaPath, modifiedContent);\n console.log(`✅ Updated schema types in: ${schemaPath}`);\n }\n\n // Remove migration files and meta directory if they exist\n const migrationDir = path.join(options.output, \"migrations\");\n\n if (fs.existsSync(migrationDir)) {\n fs.rmSync(migrationDir, { recursive: true, force: true });\n console.log(`✅ Removed: ${migrationDir}`);\n }\n\n // Read journal and remove corresponding SQL file\n if (fs.existsSync(metaDir)) {\n const journalFile = path.join(metaDir, \"_journal.json\");\n if (fs.existsSync(journalFile)) {\n const journalData = JSON.parse(fs.readFileSync(journalFile, \"utf-8\")) as JournalData;\n\n // Remove SQL files for each entry\n for (const entry of journalData.entries) {\n const sqlFile = path.join(options.output, `${entry.tag}.sql`);\n if (fs.existsSync(sqlFile)) {\n fs.rmSync(sqlFile, { force: true });\n console.log(`✅ Removed SQL file: ${entry.tag}.sql`);\n }\n }\n }\n\n // Remove meta directory after processing\n fs.rmSync(metaDir, { recursive: true, force: true });\n console.log(`✅ Removed: ${metaDir}`);\n }\n\n console.log(`✅ Successfully generated models and version metadata`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error during model generation:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\n\nimport { execSync } from \"child_process\";\n\n/**\n * Options for migration creation\n */\nexport interface CreateMigrationOptions {\n output: string;\n entitiesPath: string;\n force?: boolean;\n}\n\n/**\n * Loads the current migration version from `migrationCount.ts`.\n * @param migrationPath - Path to the migration folder.\n * @returns The latest migration version.\n */\nexport const loadMigrationVersion = async (migrationPath: string): Promise<number> => {\n try {\n const migrationCountFilePath = path.resolve(path.join(migrationPath, \"migrationCount.ts\"));\n if (!fs.existsSync(migrationCountFilePath)) {\n console.log(`✅ Current migration version: 0`);\n return 0;\n }\n\n const { MIGRATION_VERSION } = await import(migrationCountFilePath);\n console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);\n return MIGRATION_VERSION as number;\n } catch (error) {\n console.error(`❌ Error loading migrationCount:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Cleans SQL statements by removing unnecessary database options.\n * @param sql - The raw SQL statement.\n * @returns The cleaned SQL statement.\n */\nexport function cleanSQLStatement(sql: string): string {\n // Add IF NOT EXISTS to CREATE TABLE statements\n sql = sql.replace(/create\\s+table\\s+(\\w+)/gi, \"create table if not exists $1\");\n\n // Add IF NOT EXISTS to CREATE INDEX statements\n sql = sql.replace(/create\\s+index\\s+(\\w+)/gi, \"create index if not exists $1\");\n\n // Add IF NOT EXISTS to ADD INDEX statements\n sql = sql.replace(\n /alter\\s+table\\s+(\\w+)\\s+add\\s+index\\s+(\\w+)/gi,\n \"alter table $1 add index if not exists $2\",\n );\n\n // Add IF NOT EXISTS to ADD CONSTRAINT statements\n sql = sql.replace(\n /alter\\s+table\\s+(\\w+)\\s+add\\s+constraint\\s+(\\w+)/gi,\n \"alter table $1 add constraint if not exists $2\",\n );\n\n // Remove unnecessary database options\n return sql.replace(/\\s+default\\s+character\\s+set\\s+utf8mb4\\s+engine\\s*=\\s*InnoDB;?/gi, \"\").trim();\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nexport function generateMigrationFile(createStatements: string[], version: number): string {\n const versionPrefix = `v${version}_MIGRATION`;\n\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map(\n (stmt, index) =>\n ` .enqueue(\"${versionPrefix}${index}\", \"${cleanSQLStatement(stmt).replace(/\\s+/g, \" \")}\")`,\n )\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n */\nexport function saveMigrationFiles(migrationCode: string, version: number, outputDir: string) {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file with static imports\n // Build import lines for each migration version\n const importLines = [];\n for (let i = 1; i <= version; i++) {\n importLines.push(`import v${i} from \"./migrationV${i}\";`);\n }\n // Build call lines for each migration version\n const callLines = [];\n for (let i = 1; i <= version; i++) {\n callLines.push(` v${i}(migrationRunner);`);\n }\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\n${importLines.join(\"\\n\")}\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n${callLines.join(\"\\n\")}\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n}\n\n/**\n * Extracts only the relevant SQL statements for migration.\n * @param schema - The full database schema as SQL.\n * @returns Filtered list of SQL statements.\n */\nexport const extractCreateStatements = (schema: string): string[] => {\n // Split by statement-breakpoint and semicolon\n const statements = schema\n .split(/--> statement-breakpoint|;/)\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n\n return statements.filter(\n (stmt) =>\n stmt.toLowerCase().startsWith(\"create table\") ||\n stmt.toLowerCase().startsWith(\"alter table\") ||\n stmt.toLowerCase().includes(\"add index\") ||\n stmt.toLowerCase().includes(\"create index\") ||\n stmt.toLowerCase().includes(\"add unique index\") ||\n stmt.toLowerCase().includes(\"add constraint\"),\n );\n};\n\n/**\n * Creates a full database migration.\n * @param options - Database connection settings and output paths.\n */\nexport const createMigration = async (options: CreateMigrationOptions) => {\n try {\n let version = await loadMigrationVersion(options.output);\n\n if (version > 0) {\n if (options.force) {\n console.warn(\n `⚠️ Warning: Migration already exists. Creating new migration with force flag...`,\n );\n } else {\n console.error(\n `❌ Error: Migration has already been created. Use --force flag to override.`,\n );\n process.exit(1);\n }\n }\n\n // Generate SQL using drizzle-kit\n await execSync(\n `npx drizzle-kit generate --name=init --dialect mysql --out ${options.output} --schema ${options.entitiesPath}`,\n { encoding: \"utf-8\" },\n );\n const initSqlFile = path.join(options.output, \"0000_init.sql\");\n const sql = fs.readFileSync(initSqlFile, \"utf-8\");\n\n // Extract and clean statements\n const createStatements = extractCreateStatements(sql);\n\n // Generate and save migration files\n const migrationFile = generateMigrationFile(createStatements, 1);\n saveMigrationFiles(migrationFile, 1, options.output);\n\n fs.rmSync(initSqlFile, { force: true });\n console.log(`✅ Removed SQL file: ${initSqlFile}`);\n // Remove meta directory after processing\n let metaDir = path.join(options.output, \"meta\");\n fs.rmSync(metaDir, { recursive: true, force: true });\n console.log(`✅ Removed: ${metaDir}`);\n console.log(`✅ Migration successfully created!`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error during migration creation:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport mysql from \"mysql2/promise\";\nimport { MySqlTable, TableConfig } from \"drizzle-orm/mysql-core\";\nimport { RowDataPacket } from \"mysql2\";\nimport { getTableMetadata } from \"forge-sql-orm\";\nimport { AnyIndexBuilder } from \"drizzle-orm/mysql-core/indexes\";\nimport { ForeignKeyBuilder } from \"drizzle-orm/mysql-core/foreign-keys\";\nimport { UniqueConstraintBuilder } from \"drizzle-orm/mysql-core/unique-constraint\";\n\ninterface DrizzleColumn {\n type: string;\n notNull: boolean;\n autoincrement?: boolean;\n columnType?: any;\n name: string;\n getSQLType: () => string;\n}\n\ninterface DrizzleSchema {\n [tableName: string]: {\n [columnName: string]: DrizzleColumn;\n };\n}\n\ninterface DatabaseColumn extends RowDataPacket {\n TABLE_NAME: string;\n COLUMN_NAME: string;\n COLUMN_TYPE: string;\n IS_NULLABLE: string;\n COLUMN_KEY: string;\n EXTRA: string;\n}\n\ninterface DatabaseIndex extends RowDataPacket {\n TABLE_NAME: string;\n INDEX_NAME: string;\n COLUMN_NAME: string;\n NON_UNIQUE: number;\n}\n\ninterface DatabaseForeignKey extends RowDataPacket {\n TABLE_NAME: string;\n COLUMN_NAME: string;\n CONSTRAINT_NAME: string;\n REFERENCED_TABLE_NAME: string;\n REFERENCED_COLUMN_NAME: string;\n}\n\ninterface TableSchema {\n columns: Record<string, DatabaseColumn>;\n indexes: Record<\n string,\n {\n columns: string[];\n unique: boolean;\n }\n >;\n foreignKeys: Record<\n string,\n {\n column: string;\n referencedTable: string;\n referencedColumn: string;\n }\n >;\n}\n\ninterface DatabaseSchema {\n [tableName: string]: TableSchema;\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nfunction generateMigrationFile(createStatements: string[], version: number): string {\n const versionPrefix = `v${version}_MIGRATION`;\n\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map((stmt, index) => ` .enqueue(\"${versionPrefix}${index}\", \"${stmt}\")`)\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Filters out SQL statements that already exist in the previous migration file\n * @param newStatements - Array of SQL statements from new migration\n * @param prevVersion - Previous migration version\n * @param outputDir - Directory where migration files are stored\n * @returns Array of SQL statements that don't exist in previous migration\n */\nfunction filterWithPreviousMigration(\n newStatements: string[],\n prevVersion: number,\n outputDir: string,\n): string[] {\n const prevMigrationPath = path.join(outputDir, `migrationV${prevVersion}.ts`);\n\n if (!fs.existsSync(prevMigrationPath)) {\n return newStatements.map((s) => s.replace(/\\s+/g, \" \"));\n }\n\n // Read previous migration file\n const prevContent = fs.readFileSync(prevMigrationPath, \"utf-8\");\n\n // Extract SQL statements from the file\n const prevStatements = prevContent\n .split(\"\\n\")\n .filter((line) => line.includes(\".enqueue(\"))\n .map((line) => {\n const match = line.match(/\\.enqueue\\([^,]+,\\s*\"([^\"]+)\"/);\n return match ? match[1].replace(/\\s+/g, \" \").trim() : \"\";\n });\n\n // Filter out statements that already exist in previous migration\n return newStatements\n .filter((s) => !prevStatements.includes(s.replace(/\\s+/g, \" \")))\n .map((s) => s.replace(/\\s+/g, \" \"));\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n * @returns boolean indicating if migration was saved\n */\nfunction saveMigrationFiles(migrationCode: string, version: number, outputDir: string): boolean {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\nimport { MIGRATION_VERSION } from \"./migrationCount\";\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n for (let i = 1; i <= MIGRATION_VERSION; i++) {\n const migrations = (await import(\\`./migrationV\\${i}\\`)) as {\n default: MigrationType;\n };\n migrations.default(migrationRunner);\n }\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n\n return true;\n}\n\n/**\n * Loads the current migration version from `migrationCount.ts`.\n * @param migrationPath - Path to the migration folder.\n * @returns The latest migration version.\n */\nconst loadMigrationVersion = async (migrationPath: string): Promise<number> => {\n try {\n const migrationCountFilePath = path.resolve(path.join(migrationPath, \"migrationCount.ts\"));\n if (!fs.existsSync(migrationCountFilePath)) {\n console.warn(\n `⚠️ Warning: migrationCount.ts not found in ${migrationCountFilePath}, assuming no previous migrations.`,\n );\n return 0;\n }\n\n const { MIGRATION_VERSION } = await import(migrationCountFilePath);\n console.log(`✅ Current migration version: ${MIGRATION_VERSION}`);\n return MIGRATION_VERSION as number;\n } catch (error) {\n console.error(`❌ Error loading migrationCount:`, error);\n process.exit(1);\n }\n};\n\n/**\n * Gets the current database schema from MySQL including indexes and foreign keys\n * @param connection - MySQL connection\n * @param dbName - Database name\n * @returns Database schema object with indexes and foreign keys\n */\nasync function getDatabaseSchema(\n connection: mysql.Connection,\n dbName: string,\n): Promise<DatabaseSchema> {\n // Get columns\n const [columns] = await connection.execute<DatabaseColumn[]>(\n `\n SELECT TABLE_NAME, COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_KEY, EXTRA\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_SCHEMA = ?\n `,\n [dbName],\n );\n\n // Get indexes\n const [indexes] = await connection.execute<DatabaseIndex[]>(\n `\n SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, NON_UNIQUE\n FROM INFORMATION_SCHEMA.STATISTICS\n WHERE TABLE_SCHEMA = ?\n ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX\n `,\n [dbName],\n );\n\n // Get foreign keys\n const [foreignKeys] = await connection.execute<DatabaseForeignKey[]>(\n `\n SELECT \n TABLE_NAME,\n COLUMN_NAME,\n CONSTRAINT_NAME,\n REFERENCED_TABLE_NAME,\n REFERENCED_COLUMN_NAME\n FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE\n WHERE TABLE_SCHEMA = ?\n AND REFERENCED_TABLE_NAME IS NOT NULL\n `,\n [dbName],\n );\n\n const schema: DatabaseSchema = {};\n\n // Process columns\n columns.forEach((row) => {\n if (!schema[row.TABLE_NAME]) {\n schema[row.TABLE_NAME] = {\n columns: {},\n indexes: {},\n foreignKeys: {},\n };\n }\n schema[row.TABLE_NAME].columns[row.COLUMN_NAME] = row;\n });\n\n // Process indexes\n indexes.forEach((row) => {\n if (!schema[row.TABLE_NAME].indexes[row.INDEX_NAME]) {\n schema[row.TABLE_NAME].indexes[row.INDEX_NAME] = {\n columns: [],\n unique: !row.NON_UNIQUE,\n };\n }\n schema[row.TABLE_NAME].indexes[row.INDEX_NAME].columns.push(row.COLUMN_NAME);\n });\n\n // Process foreign keys\n foreignKeys.forEach((row) => {\n if (!schema[row.TABLE_NAME].foreignKeys[row.CONSTRAINT_NAME]) {\n schema[row.TABLE_NAME].foreignKeys[row.CONSTRAINT_NAME] = {\n column: row.COLUMN_NAME,\n referencedTable: row.REFERENCED_TABLE_NAME,\n referencedColumn: row.REFERENCED_COLUMN_NAME,\n };\n }\n });\n\n return schema;\n}\n\n/**\n * Converts MySQL type to normalized format for comparison\n * @param mysqlType - MySQL type from INFORMATION_SCHEMA or Drizzle type\n * @returns Normalized type string\n */\nfunction normalizeMySQLType(mysqlType: string): string {\n // Remove length/precision information\n let normalized = mysqlType.replace(/\\([^)]*\\)/, \"\").toLowerCase();\n\n // Remove 'mysql' prefix from Drizzle types\n normalized = normalized.replace(/^mysql/, \"\");\n\n return normalized;\n}\n\n/**\n * Gets the name of a foreign key constraint\n * @param fk - The foreign key builder\n * @returns The name of the foreign key constraint\n */\nfunction getForeignKeyName(fk: ForeignKeyBuilder): string {\n // @ts-ignore - Internal property access\n return fk.name;\n}\n\n/**\n * Gets the name of an index\n * @param index - The index builder\n * @returns The name of the index\n */\nfunction getIndexName(index: AnyIndexBuilder): string {\n // @ts-ignore - Internal property access\n return index.name;\n}\n\n/**\n * Gets the name of a unique constraint\n * @param uc - The unique constraint builder\n * @returns The name of the unique constraint\n */\nfunction getUniqueConstraintName(uc: UniqueConstraintBuilder): string {\n // @ts-ignore - Internal property access\n return uc.name;\n}\n\n/**\n * Gets the columns of an index\n * @param index - The index builder\n * @returns Array of column names\n */\nfunction getIndexColumns(index: AnyIndexBuilder): string[] {\n // @ts-ignore - Internal property access\n return index.columns.map((col) => col.name);\n}\n\nfunction compareForeignKey(\n fk: ForeignKeyBuilder,\n { columns }: { columns: string[]; unique: boolean },\n) {\n // @ts-ignore\n const fcolumns: string[] = fk.columns.map((c) => c.name);\n return fcolumns.sort().join(\",\") === columns.sort().join(\",\");\n}\n\n/**\n * Generates SQL changes by comparing Drizzle schema with database schema\n * @param drizzleSchema - Schema from Drizzle\n * @param dbSchema - Schema from database\n * @param schemaModule - Drizzle schema module\n * @returns Array of SQL statements\n */\nfunction generateSchemaChanges(\n drizzleSchema: DrizzleSchema,\n dbSchema: DatabaseSchema,\n schemaModule: Record<string, any>,\n): string[] {\n const changes: string[] = [];\n\n // First check existing tables in database\n for (const [tableName, dbTable] of Object.entries(dbSchema)) {\n const drizzleColumns = drizzleSchema[tableName];\n\n if (!drizzleColumns) {\n // Table exists in database but not in schema - create it\n const columns = Object.entries(dbTable.columns)\n .map(([colName, col]) => {\n const type = col.COLUMN_TYPE;\n const nullable = col.IS_NULLABLE === \"YES\" ? \"NULL\" : \"NOT NULL\";\n const autoIncrement = col.EXTRA.includes(\"auto_increment\") ? \"AUTO_INCREMENT\" : \"\";\n return `\\`${colName}\\` ${type} ${nullable} ${autoIncrement}`.trim();\n })\n .join(\",\\n \");\n\n changes.push(`CREATE TABLE if not exists \\`${tableName}\\` (\\n ${columns}\\n);`);\n\n // Create indexes for new table\n for (const [indexName, dbIndex] of Object.entries(dbTable.indexes)) {\n // Skip primary key and foreign key indexes\n if (indexName === \"PRIMARY\") {\n continue;\n }\n\n // Check if any column in this index is a foreign key\n const isForeignKeyIndex = dbIndex.columns.some((colName) => {\n const column = dbTable.columns[colName];\n return column && column.COLUMN_KEY === \"MUL\" && column.EXTRA.includes(\"foreign key\");\n });\n\n if (isForeignKeyIndex) {\n continue;\n }\n\n // Create index\n const columns = dbIndex.columns.map((col) => `\\`${col}\\``).join(\", \");\n const unique = dbIndex.unique ? \"UNIQUE \" : \"\";\n changes.push(\n `CREATE ${unique}INDEX if not exists \\`${indexName}\\` ON \\`${tableName}\\` (${columns});`,\n );\n }\n\n // Create foreign keys for new table\n for (const [fkName, dbFK] of Object.entries(dbTable.foreignKeys)) {\n changes.push(\n `ALTER TABLE \\`${tableName}\\` ADD CONSTRAINT \\`${fkName}\\` FOREIGN KEY (\\`${dbFK.column}\\`) REFERENCES \\`${dbFK.referencedTable}\\` (\\`${dbFK.referencedColumn}\\`);`,\n );\n }\n continue;\n }\n\n // Check for column changes in existing tables\n for (const [colName, dbCol] of Object.entries(dbTable.columns)) {\n const drizzleCol = Object.values(drizzleColumns).find((c) => c.name === colName);\n\n if (!drizzleCol) {\n // Column exists in database but not in schema - create it\n const type = dbCol.COLUMN_TYPE;\n const nullable = dbCol.IS_NULLABLE === \"YES\" ? \"NULL\" : \"NOT NULL\";\n changes.push(`ALTER TABLE \\`${tableName}\\` ADD COLUMN IF NOT EXISTS \\`${colName}\\` ${type} ${nullable};`);\n continue;\n }\n\n // Check for type changes\n const normalizedDbType = normalizeMySQLType(dbCol.COLUMN_TYPE);\n const normalizedDrizzleType = normalizeMySQLType(drizzleCol.getSQLType());\n\n if (normalizedDbType !== normalizedDrizzleType) {\n const type = dbCol.COLUMN_TYPE; // Use database type as source of truth\n const nullable = dbCol.IS_NULLABLE === \"YES\" ? \"NULL\" : \"NOT NULL\";\n changes.push(\n `ALTER TABLE \\`${tableName}\\` MODIFY COLUMN \\`${colName}\\` IF EXISTS ${type} ${nullable};`,\n );\n }\n }\n\n // Check for index changes\n const table = Object.values(schemaModule).find((t) => {\n const metadata = getTableMetadata(t);\n return metadata.tableName === tableName;\n });\n\n if (table) {\n const metadata = getTableMetadata(table);\n // First check indexes that exist in database but not in schema\n for (const [indexName, dbIndex] of Object.entries(dbTable.indexes)) {\n // Skip primary key and foreign key indexes\n if (indexName === \"PRIMARY\") {\n continue;\n }\n\n // Check if this is a foreign key index\n const isForeignKeyIndex = metadata.foreignKeys.some(\n (fk) => getForeignKeyName(fk) === indexName || compareForeignKey(fk, dbIndex),\n );\n if (isForeignKeyIndex) {\n continue;\n }\n\n // Check if this is a unique constraint\n const existsUniqIndex = metadata.uniqueConstraints.find(\n (uc) => getUniqueConstraintName(uc) === indexName,\n );\n let drizzleIndex = metadata.indexes.find((i) => getIndexName(i) === indexName);\n\n if (!drizzleIndex && existsUniqIndex) {\n drizzleIndex = existsUniqIndex as unknown as AnyIndexBuilder;\n }\n\n if (!drizzleIndex) {\n // Index exists in database but not in schema - create it\n const columns = dbIndex.columns.map((col) => `\\`${col}\\``).join(\", \");\n const unique = dbIndex.unique ? \"UNIQUE \" : \"\";\n changes.push(\n `CREATE ${unique}INDEX if not exists \\`${indexName}\\` ON \\`${tableName}\\` (${columns});`,\n );\n continue;\n }\n\n // Check if index columns changed\n const dbColumns = dbIndex.columns.join(\", \");\n const drizzleColumns = getIndexColumns(drizzleIndex).join(\", \");\n if (\n dbColumns !== drizzleColumns ||\n dbIndex.unique !== drizzleIndex instanceof UniqueConstraintBuilder\n ) {\n // Drop and recreate index using database values\n changes.push(`DROP INDEX \\`${indexName}\\` ON \\`${tableName}\\`;`);\n const columns = dbIndex.columns.map((col) => `\\`${col}\\``).join(\", \");\n const unique = dbIndex.unique ? \"UNIQUE \" : \"\";\n changes.push(\n `CREATE ${unique}INDEX if not exists \\`${indexName}\\` ON \\`${tableName}\\` (${columns});`,\n );\n }\n }\n\n // First check foreign keys that exist in database but not in schema\n for (const [fkName, dbFK] of Object.entries(dbTable.foreignKeys)) {\n // Find if this column is referenced in Drizzle schema\n const drizzleFK = metadata.foreignKeys.find(\n (fk) =>\n getForeignKeyName(fk) === fkName ||\n compareForeignKey(fk, { columns: [dbFK.column], unique: false }),\n );\n\n if (!drizzleFK) {\n // Foreign key exists in database but not in schema - drop it\n changes.push(\n `ALTER TABLE \\`${tableName}\\` ADD CONSTRAINT \\`${fkName}\\` FOREIGN KEY (\\`${dbFK.column}\\`) REFERENCES \\`${dbFK.referencedTable}\\` (\\`${dbFK.referencedColumn}\\`);`,\n );\n continue;\n }\n }\n\n // Then check for new foreign keys that exist in schema but not in database\n for (const drizzleForeignKey of metadata.foreignKeys) {\n // Find if this foreign key exists in database\n const isDbFk = Object.keys(dbTable.foreignKeys).find((fk) => {\n let foreignKey = dbTable.foreignKeys[fk];\n return (\n fk === getForeignKeyName(drizzleForeignKey) ||\n compareForeignKey(drizzleForeignKey, { columns: [foreignKey.column], unique: false })\n );\n });\n\n if (!isDbFk) {\n // Foreign key exists in schema but not in database - create it\n if (drizzleForeignKey) {\n const fkName = getForeignKeyName(drizzleForeignKey);\n if (fkName) {\n changes.push(`ALTER TABLE \\`${tableName}\\` DROP FOREIGN KEY \\`${fkName}\\`;`);\n } else {\n // @ts-ignore\n const columns = drizzleForeignKey.columns;\n const columnNames = columns?.length\n ? columns.map((c: any) => c.name).join(\", \")\n : \"unknown columns\";\n console.warn(\n `⚠️ Drizzle model for table '${tableName}' does not provide a name for FOREIGN KEY constraint on columns: ${columnNames}`,\n );\n }\n }\n }\n }\n }\n }\n\n return changes;\n}\n\n/**\n * Updates an existing database migration by generating schema modifications.\n * @param options - Database connection settings and output paths.\n */\nexport const updateMigration = async (options: any) => {\n try {\n let version = await loadMigrationVersion(options.output);\n const prevVersion = version;\n\n if (version < 1) {\n console.log(\n `⚠️ Initial migration not found. Run \"npx forge-sql-orm migrations:create\" first.`,\n );\n process.exit(0);\n }\n version += 1;\n\n // Create database connection\n const connection = await mysql.createConnection({\n host: options.host,\n port: options.port,\n user: options.user,\n password: options.password,\n database: options.dbName,\n });\n\n try {\n // Get current database schema\n const dbSchema = await getDatabaseSchema(connection, options.dbName);\n\n // Import Drizzle schema using absolute path\n const schemaPath = path.resolve(options.entitiesPath, \"schema.ts\");\n if (!fs.existsSync(schemaPath)) {\n throw new Error(`Schema file not found at: ${schemaPath}`);\n }\n\n const schemaModule = await import(schemaPath);\n if (!schemaModule) {\n throw new Error(`Invalid schema file at: ${schemaPath}. Schema must export tables.`);\n }\n\n // Process exported tables\n const drizzleSchema: DrizzleSchema = {};\n\n // Get all exports that are tables\n const tables = Object.values(schemaModule) as MySqlTable<TableConfig>[];\n\n tables.forEach((table) => {\n const metadata = getTableMetadata(table);\n if (metadata.tableName) {\n // Convert AnyColumn to DrizzleColumn\n const columns: Record<string, DrizzleColumn> = {};\n Object.entries(metadata.columns).forEach(([name, column]) => {\n columns[name] = {\n type: column.dataType,\n notNull: column.notNull,\n autoincrement: (column as any).autoincrement,\n columnType: column.columnType,\n name: column.name,\n getSQLType: () => column.getSQLType(),\n };\n });\n drizzleSchema[metadata.tableName] = columns;\n }\n });\n\n if (Object.keys(drizzleSchema).length === 0) {\n throw new Error(`No valid tables found in schema at: ${schemaPath}`);\n }\n\n console.log(\"Found tables:\", Object.keys(drizzleSchema));\n\n // Generate SQL changes\n const createStatements = filterWithPreviousMigration(\n generateSchemaChanges(drizzleSchema, dbSchema, schemaModule),\n prevVersion,\n options.output,\n );\n\n if (createStatements.length) {\n // Generate migration file content\n const migrationFile = generateMigrationFile(createStatements, version);\n\n // Save migration files only if there are actual changes\n if (saveMigrationFiles(migrationFile, version, options.output)) {\n console.log(`✅ Migration successfully updated!`);\n }\n process.exit(0);\n } else {\n console.log(`⚠️ No new migration changes detected.`);\n process.exit(0);\n }\n } finally {\n await connection.end();\n }\n } catch (error) {\n console.error(`❌ Error during migration update:`, error);\n process.exit(1);\n }\n};\n","import \"reflect-metadata\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { MySqlTable, TableConfig } from \"drizzle-orm/mysql-core\";\nimport { getTableMetadata, generateDropTableStatements } from \"forge-sql-orm\";\n\n/**\n * Generates a migration ID using current date\n * @returns Migration ID string with current date\n */\nfunction generateMigrationUUID(version: number): string {\n const now = new Date();\n const timestamp = now.getTime();\n return `MIGRATION_V${version}_${timestamp}`;\n}\n\n/**\n * Generates a migration file using the provided SQL statements.\n * @param createStatements - Array of SQL statements.\n * @param version - Migration version number.\n * @returns TypeScript migration file content.\n */\nfunction generateMigrationFile(createStatements: string[], version: number): string {\n const uniqId = generateMigrationUUID(version);\n // Clean each SQL statement and generate migration lines with .enqueue()\n const migrationLines = createStatements\n .map(\n (stmt, index) => ` .enqueue(\"${uniqId}_${index}\", \\\"${stmt}\\\")`, // eslint-disable-line no-useless-escape\n )\n .join(\"\\n\");\n\n // Migration template\n return `import { MigrationRunner } from \"@forge/sql/out/migration\";\n\nexport default (migrationRunner: MigrationRunner): MigrationRunner => {\n return migrationRunner\n${migrationLines};\n};`;\n}\n\n/**\n * Saves the generated migration file along with `migrationCount.ts` and `index.ts`.\n * @param migrationCode - The migration code to be written to the file.\n * @param version - Migration version number.\n * @param outputDir - Directory where the migration files will be saved.\n */\nfunction saveMigrationFiles(migrationCode: string, version: number, outputDir: string) {\n if (!fs.existsSync(outputDir)) {\n fs.mkdirSync(outputDir, { recursive: true });\n }\n\n const migrationFilePath = path.join(outputDir, `migrationV${version}.ts`);\n const migrationCountPath = path.join(outputDir, `migrationCount.ts`);\n const indexFilePath = path.join(outputDir, `index.ts`);\n\n // Write the migration file\n fs.writeFileSync(migrationFilePath, migrationCode);\n\n // Write the migration count file\n fs.writeFileSync(migrationCountPath, `export const MIGRATION_VERSION = ${version};`);\n\n // Generate the migration index file\n const indexFileContent = `import { MigrationRunner } from \"@forge/sql/out/migration\";\nimport { MIGRATION_VERSION } from \"./migrationCount\";\n\nexport type MigrationType = (\n migrationRunner: MigrationRunner,\n) => MigrationRunner;\n\nexport default async (\n migrationRunner: MigrationRunner,\n): Promise<MigrationRunner> => {\n for (let i = 1; i <= MIGRATION_VERSION; i++) {\n const migrations = (await import(\\`./migrationV\\${i}\\`)) as {\n default: MigrationType;\n };\n migrations.default(migrationRunner);\n }\n return migrationRunner;\n};`;\n\n fs.writeFileSync(indexFilePath, indexFileContent);\n\n console.log(`✅ Migration file created: ${migrationFilePath}`);\n console.log(`✅ Migration count file updated: ${migrationCountPath}`);\n console.log(`✅ Migration index file created: ${indexFilePath}`);\n}\n\n/**\n * Creates a full database migration.\n * @param options - Database connection settings and output paths.\n */\nexport const dropMigration = async (options: any) => {\n try {\n // Start from version 1 if no previous migrations exist\n const version = 1;\n\n // Import Drizzle schema using absolute path\n const schemaPath = path.resolve(options.entitiesPath, \"schema.ts\");\n if (!fs.existsSync(schemaPath)) {\n throw new Error(`Schema file not found at: ${schemaPath}`);\n }\n\n const schemaModule = await import(schemaPath);\n if (!schemaModule) {\n throw new Error(`Invalid schema file at: ${schemaPath}. Schema must export tables.`);\n }\n\n // Get all exports that are tables\n const tables = Object.values(schemaModule) as MySqlTable<TableConfig>[];\n\n if (tables.length === 0) {\n throw new Error(`No valid tables found in schema at: ${schemaPath}`);\n }\n\n // Get table names for logging\n const tableNames = tables\n .map((table) => {\n const metadata = getTableMetadata(table);\n return metadata.tableName;\n })\n .filter(Boolean);\n\n console.log(\"Found tables:\", tableNames);\n\n // Generate drop statements\n const dropStatements = generateDropTableStatements(tableNames);\n\n // Generate and save migration files\n const migrationFile = generateMigrationFile(dropStatements, version);\n saveMigrationFiles(migrationFile, version, options.output);\n\n console.log(`✅ Migration successfully created!`);\n process.exit(0);\n } catch (error) {\n console.error(`❌ Error during migration creation:`, error);\n process.exit(1);\n }\n};\n","#!/usr/bin/env node\n\nimport { Command } from \"commander\";\nimport dotenv from \"dotenv\";\nimport inquirer from \"inquirer\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { generateModels } from \"./actions/generate-models\";\nimport { createMigration } from \"./actions/migrations-create\";\nimport { updateMigration } from \"./actions/migrations-update\";\nimport { dropMigration } from \"./actions/migrations-drops\";\n\nconst ENV_PATH = path.resolve(process.cwd(), \".env\");\n// 🔄 Load environment variables from `.env` file\ndotenv.config({ path: ENV_PATH });\n\nconst saveEnvFile = (config: any) => {\n let envContent = \"\";\n const envFilePath = ENV_PATH;\n\n if (fs.existsSync(envFilePath)) {\n envContent = fs.readFileSync(envFilePath, \"utf8\");\n }\n\n const envVars = envContent\n .split(\"\\n\")\n .filter((line) => line.trim() !== \"\" && !line.startsWith(\"#\"))\n .reduce((acc: any, line) => {\n const [key, ...value] = line.split(\"=\");\n acc[key] = value.join(\"=\");\n return acc;\n }, {});\n\n Object.entries(config).forEach(([key, value]) => {\n envVars[`FORGE_SQL_ORM_${key.toUpperCase()}`] = value;\n });\n\n const updatedEnvContent = Object.entries(envVars)\n .map(([key, value]) => `${key}=${value}`)\n .join(\"\\n\");\n\n fs.writeFileSync(envFilePath, updatedEnvContent, { encoding: \"utf8\" });\n\n console.log(\"✅ Configuration saved to .env without overwriting other variables.\");\n};\n\n/**\n * Prompts the user for missing parameters using Inquirer.js.\n * @param config - The current configuration object.\n * @param defaultOutput - Default output path.\n * @param customAskMissingParams - Optional function for additional prompts.\n * @returns Updated configuration with user input.\n */\nconst askMissingParams = async (\n config: any,\n defaultOutput: string,\n customAskMissingParams?: (cfg: any, questions: unknown[]) => void,\n) => {\n const questions: unknown[] = [];\n\n if (!config.host)\n questions.push({\n type: \"input\",\n name: \"host\",\n message: \"Enter database host:\",\n default: \"localhost\",\n });\n\n if (!config.port)\n questions.push({\n type: \"input\",\n name: \"port\",\n message: \"Enter database port:\",\n default: \"3306\",\n validate: (input: string) => !isNaN(parseInt(input, 10)),\n });\n\n if (!config.user)\n questions.push({\n type: \"input\",\n name: \"user\",\n message: \"Enter database user:\",\n default: \"root\",\n });\n\n if (!config.password)\n questions.push({\n type: \"password\",\n name: \"password\",\n message: \"Enter database password:\",\n mask: \"*\",\n });\n\n if (!config.dbName)\n questions.push({\n type: \"input\",\n name: \"dbName\",\n message: \"Enter database name:\",\n });\n\n if (!config.output)\n questions.push({\n type: \"input\",\n name: \"output\",\n message: \"Enter output path:\",\n default: defaultOutput,\n });\n\n // Allow additional questions from the caller\n if (customAskMissingParams) {\n customAskMissingParams(config, questions);\n }\n\n // If there are missing parameters, prompt the user\n if (questions.length > 0) {\n // @ts-ignore - Ignore TypeScript warning for dynamic question type\n const answers = await inquirer.prompt(questions);\n return { ...config, ...answers, port: parseInt(config.port ?? answers.port, 10) };\n }\n\n return config;\n};\n\n/**\n * Retrieves configuration parameters from command-line arguments and environment variables.\n * If any required parameters are missing, prompts the user for input.\n * @param cmd - The command object containing CLI options.\n * @param defaultOutput - Default output directory.\n * @param customConfig - Optional function for additional configuration parameters.\n * @param customAskMissingParams - Optional function for additional prompts.\n * @returns A fully resolved configuration object.\n */\nconst getConfig = async (\n cmd: any,\n defaultOutput: string,\n customConfig?: () => any,\n customAskMissingParams?: (cfg: any, questions: unknown[]) => void,\n) => {\n let config = {\n host: cmd.host || process.env.FORGE_SQL_ORM_HOST,\n port: cmd.port\n ? parseInt(cmd.port, 10)\n : process.env.FORGE_SQL_ORM_PORT\n ? parseInt(process.env.FORGE_SQL_ORM_PORT, 10)\n : undefined,\n user: cmd.user || process.env.FORGE_SQL_ORM_USER,\n password: cmd.password || process.env.FORGE_SQL_ORM_PASSWORD,\n dbName: cmd.dbName || process.env.FORGE_SQL_ORM_DBNAME,\n output: cmd.output || process.env.FORGE_SQL_ORM_OUTPUT,\n };\n\n // Merge additional configurations if provided\n if (customConfig) {\n config = { ...config, ...customConfig() };\n }\n\n const conf = await askMissingParams(config, defaultOutput, customAskMissingParams);\n if (cmd.saveEnv) {\n saveEnvFile(conf);\n }\n return conf;\n};\n\n// 📌 Initialize CLI\nexport const program = new Command();\nprogram.version(\"1.0.0\");\n\n// ✅ Command: Generate database models (Entities)\nprogram\n .command(\"generate:model\")\n .description(\"Generate Drizzle models from the database.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for entities\")\n .option(\"--versionField <string>\", \"Field name for versioning\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/entities\",\n () => ({\n versionField: cmd.versionField || process.env.FORGE_SQL_ORM_VERSIONFIELD,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.versionField) {\n questions.push({\n type: \"input\",\n name: \"versionField\",\n message: \"Enter the field name for versioning (leave empty to skip):\",\n default: \"\",\n });\n }\n },\n );\n await generateModels(config);\n });\n\n// ✅ Command: Create initial database migration\nprogram\n .command(\"migrations:create\")\n .description(\"Generate an initial migration for the entire database.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--force\", \"Force creation even if migrations exist\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n force: cmd.force || false,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await createMigration(config);\n });\n\n// ✅ Command: Update migration for schema changes\nprogram\n .command(\"migrations:update\")\n .description(\"Generate a migration to update the database schema.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await updateMigration(config);\n });\n\n// ✅ Command: Drop all migrations\nprogram\n .command(\"migrations:drop\")\n .description(\"Generate a migration to drop all tables and clear migrations history.\")\n .option(\"--host <string>\", \"Database host\")\n .option(\"--port <number>\", \"Database port\")\n .option(\"--user <string>\", \"Database user\")\n .option(\"--password <string>\", \"Database password\")\n .option(\"--dbName <string>\", \"Database name\")\n .option(\"--output <string>\", \"Output path for migrations\")\n .option(\"--entitiesPath <string>\", \"Path to the folder containing entities\")\n .option(\"--saveEnv\", \"Save configuration to .env file\")\n .action(async (cmd) => {\n const config = await getConfig(\n cmd,\n \"./database/migration\",\n () => ({\n entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,\n }),\n (cfg, questions: unknown[]) => {\n if (!cfg.entitiesPath)\n questions.push({\n type: \"input\",\n name: \"entitiesPath\",\n message: \"Enter the path to entities:\",\n default: \"./database/entities\",\n });\n },\n );\n await dropMigration(config);\n });\n\n// 🔥 Execute CLI\n program.parse(process.argv);\n"],"names":["loadMigrationVersion","generateMigrationFile","saveMigrationFiles","columns","drizzleColumns"],"mappings":";;;;;;;;;;;AAuFA,SAAS,kBAAkB,eAA+B;AAExD,QAAM,UAAU;AAAA;AAAA;AAGhB,MAAI,kBAAkB,cAEnB;AAAA,IACC;AAAA,IACA;AAAA,EAAA,EAGD,QAAQ,iCAAiC,2BAA2B,EAEpE,QAAQ,qDAAqD,uBAAuB,EAEpF,QAAQ,+DAA+D,uBAAuB,EAE9F,QAAQ,6BAA6B,uBAAuB,EAE5D,QAAQ,iDAAiD,mBAAmB,EAE5E,QAAQ,+DAA+D,uBAAuB,EAE9F,QAAQ,6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gBAAgB,MAAM;AAC9B,CAAC;AAGH,QACG,QAAQ,iBAAiB,EACzB,YAAY,uEAAuE,EACnF,OAAO,mBAAmB,eAAe,EACzC,OAAO,mBAAmB,eAAe,EACzC,OAAO,mBAAmB,eAAe,EACzC,OAAO,uBAAuB,mBAAmB,EACjD,OAAO,qBAAqB,eAAe,EAC3C,OAAO,qBAAqB,4BAA4B,EACxD,OAAO,2BAA2B,wCAAwC,EAC1E,OAAO,aAAa,iCAAiC,EACrD,OAAO,OAAO,QAAQ;AACrB,QAAM,SAAS,MAAM;AAAA,IACnB;AAAA,IACA;AAAA,IACA,OAAO;AAAA,MACL,cAAc,IAAI,gBAAgB,QAAQ,IAAI;AAAA,IAAA;AAAA,IAEhD,CAAC,KAAK,cAAyB;AAC7B,UAAI,CAAC,IAAI;AACP,kBAAU,KAAK;AAAA,UACb,MAAM;AAAA,UACN,MAAM;AAAA,UACN,SAAS;AAAA,UACT,SAAS;AAAA,QAAA,CACV;AAAA,IACL;AAAA,EAAA;AAEF,QAAM,cAAc,MAAM;AAC5B,CAAC;AAGD,QAAQ,MAAM,QAAQ,IAAI;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"forgeSqlOrmCLI.js","sources":["../src/forgeSqlOrmCLI.
|
|
1
|
+
{"version":3,"file":"forgeSqlOrmCLI.js","sources":["../src/forgeSqlOrmCLI.mts"],"sourcesContent":["#!/usr/bin/env node\nimport {execSync} from 'child_process'\nimport path from \"path\";\nimport { fileURLToPath } from 'url';\nimport { dirname } from 'path';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n// Get CLI arguments (excluding \"node\" and script path)\nconst args = process.argv.slice(2).join(\" \");\n\n// Resolve the path to cli.ts (your TypeScript entry file)\nconst cliPath = path.resolve(__dirname, \"cli.mjs\");\n\ntry {\n execSync(`npx --yes tsm --no-warnings \"${cliPath}\" ${args}`, { stdio: \"inherit\" });\n process.exit(0);\n} catch (e:any) {\n console.error(\"⚠️ Command execution failed:\", e.message);\n process.exit(1);\n}"],"names":["__filename","fileURLToPath","__dirname","dirname","execSync"],"mappings":";;;;;;AAMA,MAAMA,eAAaC,IAAAA,wQAA6B;AAChD,MAAMC,cAAYC,KAAAA,QAAQH,YAAU;AAEpC,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC,EAAE,KAAK,GAAG;AAG3C,MAAM,UAAU,KAAK,QAAQE,aAAW,SAAS;AAEjD,IAAI;AACAE,yBAAS,iCAAiC,OAAO,KAAK,IAAI,IAAI,EAAE,OAAO,WAAW;AAClF,UAAQ,KAAK,CAAC;AAClB,SAAS,GAAO;AACZ,UAAQ,MAAM,iCAAiC,EAAE,OAAO;AACxD,UAAQ,KAAK,CAAC;AAClB;"}
|
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
import { execSync } from "child_process";
|
|
3
3
|
import path, { dirname } from "path";
|
|
4
4
|
import { fileURLToPath } from "url";
|
|
5
|
-
const __filename = fileURLToPath(import.meta.url);
|
|
6
|
-
const __dirname = dirname(__filename);
|
|
5
|
+
const __filename$1 = fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname$1 = dirname(__filename$1);
|
|
7
7
|
const args = process.argv.slice(2).join(" ");
|
|
8
|
-
const cliPath = path.resolve(__dirname, "cli.mjs");
|
|
8
|
+
const cliPath = path.resolve(__dirname$1, "cli.mjs");
|
|
9
9
|
try {
|
|
10
10
|
execSync(`npx --yes tsm --no-warnings "${cliPath}" ${args}`, { stdio: "inherit" });
|
|
11
11
|
process.exit(0);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"forgeSqlOrmCLI.mjs","sources":["../src/forgeSqlOrmCLI.
|
|
1
|
+
{"version":3,"file":"forgeSqlOrmCLI.mjs","sources":["../src/forgeSqlOrmCLI.mts"],"sourcesContent":["#!/usr/bin/env node\nimport {execSync} from 'child_process'\nimport path from \"path\";\nimport { fileURLToPath } from 'url';\nimport { dirname } from 'path';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n// Get CLI arguments (excluding \"node\" and script path)\nconst args = process.argv.slice(2).join(\" \");\n\n// Resolve the path to cli.ts (your TypeScript entry file)\nconst cliPath = path.resolve(__dirname, \"cli.mjs\");\n\ntry {\n execSync(`npx --yes tsm --no-warnings \"${cliPath}\" ${args}`, { stdio: \"inherit\" });\n process.exit(0);\n} catch (e:any) {\n console.error(\"⚠️ Command execution failed:\", e.message);\n process.exit(1);\n}"],"names":["__filename","__dirname"],"mappings":";;;;AAMA,MAAMA,eAAa,cAAc,YAAY,GAAG;AAChD,MAAMC,cAAY,QAAQD,YAAU;AAEpC,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC,EAAE,KAAK,GAAG;AAG3C,MAAM,UAAU,KAAK,QAAQC,aAAW,SAAS;AAEjD,IAAI;AACA,WAAS,iCAAiC,OAAO,KAAK,IAAI,IAAI,EAAE,OAAO,WAAW;AAClF,UAAQ,KAAK,CAAC;AAClB,SAAS,GAAO;AACZ,UAAQ,MAAM,iCAAiC,EAAE,OAAO;AACxD,UAAQ,KAAK,CAAC;AAClB;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "forge-sql-orm-cli",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.13",
|
|
4
4
|
"description": "CLI tool for Forge SQL ORM",
|
|
5
5
|
"main": "dist-cli/cli.js",
|
|
6
6
|
"types": "dist-cli/cli.d.ts",
|
|
@@ -44,27 +44,34 @@
|
|
|
44
44
|
"dependencies": {
|
|
45
45
|
"commander": "^14.0.2",
|
|
46
46
|
"dotenv": "^17.2.3",
|
|
47
|
-
"drizzle-kit": "^0.31.
|
|
47
|
+
"drizzle-kit": "^0.31.7",
|
|
48
48
|
"drizzle-orm": "^0.44.7",
|
|
49
|
-
"forge-sql-orm": "^2.1.
|
|
50
|
-
"inquirer": "^
|
|
49
|
+
"forge-sql-orm": "^2.1.13",
|
|
50
|
+
"inquirer": "^13.0.1",
|
|
51
51
|
"mysql2": "^3.15.3",
|
|
52
52
|
"reflect-metadata": "^0.2.2"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
|
-
"@eslint/js": "^9.
|
|
56
|
-
"@types/node": "^24.
|
|
57
|
-
"@typescript-eslint/eslint-plugin": "^8.
|
|
58
|
-
"@typescript-eslint/parser": "^8.
|
|
55
|
+
"@eslint/js": "^9.39.1",
|
|
56
|
+
"@types/node": "^24.10.1",
|
|
57
|
+
"@typescript-eslint/eslint-plugin": "^8.47.0",
|
|
58
|
+
"@typescript-eslint/parser": "^8.47.0",
|
|
59
59
|
"eslint-config-prettier": "^10.1.8",
|
|
60
60
|
"eslint-plugin-import": "^2.32.0",
|
|
61
|
-
"knip": "^5.
|
|
61
|
+
"knip": "^5.70.1",
|
|
62
62
|
"reflect-metadata": "^0.2.2",
|
|
63
63
|
"typescript": "^5.9.3",
|
|
64
|
-
"vite": "^7.
|
|
64
|
+
"vite": "^7.2.4"
|
|
65
65
|
},
|
|
66
|
-
"
|
|
67
|
-
"
|
|
68
|
-
|
|
66
|
+
"lint-staged": {
|
|
67
|
+
"*.{ts,tsx,css,scss,md}": [
|
|
68
|
+
"prettier --write",
|
|
69
|
+
"eslint --fix"
|
|
70
|
+
]
|
|
71
|
+
},
|
|
72
|
+
"husky": {
|
|
73
|
+
"hooks": {
|
|
74
|
+
"pre-commit": "cd .husky && ./pre-commit"
|
|
75
|
+
}
|
|
69
76
|
}
|
|
70
77
|
}
|
|
@@ -155,6 +155,13 @@ export const generateModels = async (options: GenerateModelsOptions) => {
|
|
|
155
155
|
for (const [tableName, tableData] of Object.entries(snapshotData.tables)) {
|
|
156
156
|
const table = tableData as TableMetadata;
|
|
157
157
|
|
|
158
|
+
// Check if table name starts with 'a_' and warn about cache
|
|
159
|
+
if (tableName.toLowerCase().startsWith("a_")) {
|
|
160
|
+
console.warn(
|
|
161
|
+
`⚠️ Table "${tableName}" starts with "a_". KVS Cache will not work with this table because such tables are ignored in cache operations.`,
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
|
|
158
165
|
// Find version field in columns
|
|
159
166
|
const versionField = Object.entries(table.columns).find(
|
|
160
167
|
([_, col]) => col.name.toLowerCase() === options.versionField,
|
package/tsconfig.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"compilerOptions": {
|
|
3
3
|
"target": "esnext",
|
|
4
|
-
"module": "
|
|
4
|
+
"module": "NodeNext",
|
|
5
5
|
"lib": ["esnext"],
|
|
6
6
|
"declaration": true,
|
|
7
7
|
"outDir": "./dist-cli",
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
"esModuleInterop": true,
|
|
11
11
|
"skipLibCheck": true,
|
|
12
12
|
"forceConsistentCasingInFileNames": true,
|
|
13
|
-
"moduleResolution": "
|
|
13
|
+
"moduleResolution": "NodeNext"
|
|
14
14
|
},
|
|
15
15
|
"include": ["src/**/*"],
|
|
16
16
|
"exclude": ["node_modules", "dist-cli"]
|
|
File without changes
|
|
File without changes
|