-
-
Notifications
You must be signed in to change notification settings - Fork 34
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add generate migraiton helper utility
- Loading branch information
Showing
7 changed files
with
256 additions
and
5 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,5 @@ | ||
export * from './context'; | ||
export * from './migration'; | ||
export * from './query'; | ||
export * from './schema'; | ||
export * from './type'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,129 @@ | ||
import { pascalCase } from 'pascal-case'; | ||
import path from 'node:path'; | ||
import fs from 'node:fs'; | ||
import process from 'node:process'; | ||
import { MigrationGenerateCommand } from 'typeorm/commands/MigrationGenerateCommand'; | ||
import type { MigrationGenerateCommandContext, MigrationGenerateResult } from './type'; | ||
|
||
class GenerateCommand extends MigrationGenerateCommand { | ||
static prettify(query: string) { | ||
return this.prettifyQuery(query); | ||
} | ||
} | ||
|
||
function queryParams(parameters: any[] | undefined): string { | ||
if (!parameters || !parameters.length) { | ||
return ''; | ||
} | ||
|
||
return `, ${JSON.stringify(parameters)}`; | ||
} | ||
|
||
function buildTemplate( | ||
name: string, | ||
timestamp: number, | ||
upStatements: string[], | ||
downStatements: string[], | ||
): string { | ||
const migrationName = `${pascalCase(name)}${timestamp}`; | ||
|
||
const up = upStatements.map((statement) => ` ${statement}`); | ||
const down = downStatements.map((statement) => ` ${statement}`); | ||
|
||
return `import { MigrationInterface, QueryRunner } from 'typeorm'; | ||
export class ${migrationName} implements MigrationInterface { | ||
name = '${migrationName}'; | ||
public async up(queryRunner: QueryRunner): Promise<void> { | ||
${up.join(` | ||
`)} | ||
} | ||
public async down(queryRunner: QueryRunner): Promise<void> { | ||
${down.join(` | ||
`)} | ||
} | ||
} | ||
`; | ||
} | ||
|
||
export async function generateMigration( | ||
context: MigrationGenerateCommandContext, | ||
) : Promise<MigrationGenerateResult> { | ||
context.name = context.name || 'Default'; | ||
|
||
const timestamp = context.timestamp || new Date().getTime(); | ||
const fileName = `${timestamp}-${context.name}.ts`; | ||
|
||
const { dataSource } = context; | ||
|
||
const up: string[] = []; const | ||
down: string[] = []; | ||
|
||
if (!dataSource.isInitialized) { | ||
await dataSource.initialize(); | ||
} | ||
|
||
const sqlInMemory = await dataSource.driver.createSchemaBuilder().log(); | ||
|
||
if (context.prettify) { | ||
sqlInMemory.upQueries.forEach((upQuery) => { | ||
upQuery.query = GenerateCommand.prettify( | ||
upQuery.query, | ||
); | ||
}); | ||
sqlInMemory.downQueries.forEach((downQuery) => { | ||
downQuery.query = GenerateCommand.prettify( | ||
downQuery.query, | ||
); | ||
}); | ||
} | ||
|
||
sqlInMemory.upQueries.forEach((upQuery) => { | ||
up.push(`await queryRunner.query(\`${upQuery.query.replace(/`/g, '\\`')}\`${queryParams(upQuery.parameters)});`); | ||
}); | ||
|
||
sqlInMemory.downQueries.forEach((downQuery) => { | ||
down.push(`await queryRunner.query(\`${downQuery.query.replace(/`/g, '\\`')}\`${queryParams(downQuery.parameters)});`); | ||
}); | ||
|
||
await dataSource.destroy(); | ||
|
||
if ( | ||
up.length === 0 && | ||
down.length === 0 | ||
) { | ||
return { up, down }; | ||
} | ||
|
||
const content = buildTemplate(context.name, timestamp, up, down.reverse()); | ||
|
||
if (!context.preview) { | ||
let directoryPath : string; | ||
if (context.directoryPath) { | ||
if (!path.isAbsolute(context.directoryPath)) { | ||
directoryPath = path.join(process.cwd(), context.directoryPath); | ||
} else { | ||
directoryPath = context.directoryPath; | ||
} | ||
} else { | ||
directoryPath = path.join(process.cwd(), 'migrations'); | ||
} | ||
|
||
try { | ||
await fs.promises.access(directoryPath, fs.constants.R_OK | fs.constants.W_OK); | ||
} catch (e) { | ||
await fs.promises.mkdir(directoryPath, { recursive: true }); | ||
} | ||
|
||
const filePath = path.join(directoryPath, fileName); | ||
|
||
await fs.promises.writeFile(filePath, content, { encoding: 'utf-8' }); | ||
} | ||
|
||
return { | ||
up, | ||
down, | ||
content, | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import type { DataSource } from 'typeorm'; | ||
|
||
export type MigrationGenerateResult = { | ||
up: string[], | ||
down: string[], | ||
content?: string | ||
}; | ||
|
||
export type MigrationGenerateCommandContext = { | ||
/** | ||
* Directory where the migration(s) should be stored. | ||
*/ | ||
directoryPath?: string, | ||
/** | ||
* Name of the migration class. | ||
*/ | ||
name?: string, | ||
/** | ||
* DataSource used for reference of existing schema. | ||
*/ | ||
dataSource: DataSource, | ||
|
||
/** | ||
* Timestamp in milliseconds. | ||
*/ | ||
timestamp?: number, | ||
|
||
/** | ||
* Prettify sql statements. | ||
*/ | ||
prettify?: boolean, | ||
|
||
/** | ||
* Only return up- & down-statements instead of backing up the migration to the file system. | ||
*/ | ||
preview?: boolean | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
import {DataSource, DataSourceOptions} from "typeorm"; | ||
import {generateMigration} from "../../../src"; | ||
import {User} from "../../data/entity/user"; | ||
|
||
describe('src/database/migration', () => { | ||
it('should generate migration file', async () => { | ||
const options : DataSourceOptions = { | ||
type: 'better-sqlite3', | ||
entities: [User], | ||
database: ':memory:', | ||
extra: { | ||
charset: "UTF8_GENERAL_CI" | ||
} | ||
} | ||
const dataSource = new DataSource(options); | ||
|
||
const output = await generateMigration({ | ||
dataSource, | ||
preview: true | ||
}); | ||
|
||
expect(output).toBeDefined(); | ||
expect(output.up).toBeDefined(); | ||
expect(output.up.length).toBeGreaterThanOrEqual(1); | ||
expect(output.up[0]).toEqual('await queryRunner.query(`CREATE TABLE "user" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "firstName" varchar NOT NULL, "lastName" varchar NOT NULL, "email" varchar NOT NULL, "foo" varchar NOT NULL)`);') | ||
|
||
expect(output.down).toBeDefined(); | ||
expect(output.down.length).toBeGreaterThanOrEqual(1); | ||
expect(output.down[0]).toEqual('await queryRunner.query(`DROP TABLE "user"`);') | ||
}) | ||
}) |