Skip to content

Commit

Permalink
fix multiple bugs found
Browse files Browse the repository at this point in the history
  • Loading branch information
spersico committed Jan 17, 2025
1 parent bfdde54 commit 02fc369
Show file tree
Hide file tree
Showing 12 changed files with 135 additions and 97 deletions.
21 changes: 11 additions & 10 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "prisma-migration-migrator",
"version": "0.0.19",
"version": "0.0.24",
"description": "Replace Prisma as the migration engine with Knex, while keeping it as ORM",
"type": "module",
"author": "spersico",
Expand All @@ -10,12 +10,13 @@
"/dist"
],
"bin": {
"prisma-migration-migrator": "dist/index.js"
"prisma-migration-migrator": "dist/bin.js"
},
"main": "dist/index.js",
"scripts": {
"build": "rm -rf dist && rm -rf tsconfig.build.tsbuildinfo && tsc --project tsconfig.build.json",
"test:migrate:build": "npm run build && node ./dist/index.js",
"test:migrate": "tsx src/index.ts",
"test:migrate": "tsx src/bin.ts",
"test:cleanup": "tsx src/tests/helpers/util-cleanup.ts",
"test:knex:sync": "knex migrate:latest",
"test:manual": "npm run test:prisma:create && npm run test:migrate && npm run test:knex:sync",
Expand All @@ -26,8 +27,7 @@
"chalk": "^5.4.1",
"inquirer": "^12.3.2",
"prisma-diff-to-knex-migration": "^1.0.14",
"sql-query-identifier": "^2.8.0",
"@prisma/client": "*"
"sql-query-identifier": "^2.8.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
Expand All @@ -46,6 +46,7 @@
"pg": "^8.13.1",
"prettier": "^3.4.2",
"prisma": "^6.2.1",
"@prisma/client": "^6.2.1",
"tsx": "^4.19.2",
"typescript": "^5.7.3"
},
Expand Down
44 changes: 44 additions & 0 deletions src/bin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/usr/bin/env node
import { setup } from './setup/index.mjs';
import { executeMigrationWorkflow } from './index.js';

function getFlags(argv): Record<string, string | boolean> {
const filterArgs = (flag) => flag.includes('--');
const mapFlags = (flag) => flag.split('--')[1].split('=');
const args = argv.slice(2).filter(filterArgs).map(mapFlags);
const flagsObj = {};

for (const arg of args) {
flagsObj[arg[0]] = arg[1] || true;
}
return flagsObj;
}

// Entry point for the CLI
async function main() {
const flags: {
setup?: boolean;
'skip-check'?: boolean;
'prisma-folder-path'?: string;
} = getFlags(process.argv);

if (flags.setup) {
await setup();
} else {
const skipCheck = !!flags['skip-check'];
const prismaFolderPath =
flags['prisma-folder-path'] &&
typeof flags['prisma-folder-path'] === 'string'
? flags['prisma-folder-path']
: 'prisma';
try {
await executeMigrationWorkflow({ skipCheck, prismaFolderPath });
process.exit(0);
} catch (error) {
console.error(error);
process.exit(1);
}
}
}

main();
55 changes: 4 additions & 51 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
#!/usr/bin/env node

import { fileURLToPath } from 'node:url';
import type { MigratorParameters } from './migrator/types.js';
import { migrator } from './migrator/index.js';
import { setup } from './setup/index.mjs';
import { checkIfSetupIsNeeded } from './setup/pre-check.mjs';
import { errorLog, successLog, warningLog } from './setup/textStyles.mjs';

// Function to execute the migrator
async function executeMigrator({
export async function executeMigrationWorkflow({
skipCheck,
prismaFolderPath,
}: {
Expand Down Expand Up @@ -40,54 +36,11 @@ async function executeMigrator({
successLog(
`Migrations converted successfully. Check the migrations directory.`,
);
process.exit(0);
} catch (err) {
errorLog(
`Error converting migrations. Check the error message below for more information.`,
);
console.error(err);
process.exit(1);
errorLog(`Error converting migrations`);
throw err;
}
}

function getFlags(argv): Record<string, string | boolean> {
const filterArgs = (flag) => flag.includes('--');
const mapFlags = (flag) => flag.split('--')[1].split('=');
const args = argv.slice(2).filter(filterArgs).map(mapFlags);
const flagsObj = {};

for (const arg of args) {
flagsObj[arg[0]] = arg[1] || true;
}
return flagsObj;
}

// Main function to handle command-line arguments
async function main() {
const flags: {
setup?: boolean;
'skip-check'?: boolean;
'prisma-folder-path'?: string;
} = getFlags(process.argv);

if (flags.setup) {
await setup();
} else {
const skipCheck = !!flags['skip-check'];
const prismaFolderPath =
flags['prisma-folder-path'] &&
typeof flags['prisma-folder-path'] === 'string'
? flags['prisma-folder-path']
: 'prisma';

await executeMigrator({ skipCheck, prismaFolderPath });
}
}

// If the script is run directly, execute the main function
if (process.argv[1] === fileURLToPath(import.meta.url)) {
main();
}

export type { MigratorParameters };
export { migrator };
export type { MigratorParameters as ConvertPrismaMigrationsToKnexMigrationsParameters };
4 changes: 1 addition & 3 deletions src/migrator/directories.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { mkdir } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import type { MigratorParameters } from './types.js';
import { findKnexfile } from './knexfileFinder.js';
Expand Down Expand Up @@ -73,8 +72,7 @@ async function getOutputDirectory(
}

export function getBaseDirectory() {
const __filename = fileURLToPath(import.meta.url);
return path.resolve(path.dirname(__filename), '..', '..');
return process.cwd();
}

/**
Expand Down
70 changes: 59 additions & 11 deletions src/migrator/syncMigrationTables.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
import { PrismaClient } from '@prisma/client';
import { knexMigrationsLockSql, knexMigrationsSQl } from './constants.js';
import {
confirmationPrompt,
errorLog,
textImportant,
textTitle,
} from './../setup/textStyles.mjs';
import path from 'node:path';
import { getBaseDirectory } from './directories.js';
import type { PrismaClient } from '@prisma/client';

const PrismatoKnexSQL = `
INSERT INTO knex_migrations (name, batch, migration_time)
SELECT migration_name || '.mjs', 1, finished_at
FROM _prisma_migrations
WHERE migration_name NOT IN (
SELECT name
FROM knex_migrations
)
`;

async function checkIfTableIsPresent(
prisma: PrismaClient,
Expand Down Expand Up @@ -34,23 +52,53 @@ async function createKnexMigrationsTable(prisma: PrismaClient): Promise<void> {
async function syncKnexAndPrismaMigrations(
prisma: PrismaClient,
): Promise<void> {
const res = await prisma.$executeRawUnsafe<number>(`
INSERT INTO knex_migrations (name, batch, migration_time)
SELECT migration_name || '.mjs', 1, finished_at
FROM _prisma_migrations
WHERE migration_name NOT IN (
SELECT name
FROM knex_migrations
)
`);
const res = await prisma.$executeRawUnsafe<number>(PrismatoKnexSQL);
console.log(`> > Synced ${res} migrations from Prisma to Knex`);
}

export async function syncMigrationTables(): Promise<void> {
const continues = await confirmationPrompt(
`${textTitle('-------------------------\nKnex-Prisma History Sync\n---------------------------')}
Optionally, you can update your Knex Migrations table with the migrations that Prisma has already applied.
That way, if in your project you have already run migrations with Prisma, you can keep track of them.
To do this, the script will check in the DB connected to the local @prisma/client if the tables '_prisma_migrations' and 'knex_migrations' exist.
If they don't, it will create them for you. Then, it will copy the migrations from the Prisma Migrations history table to knex_migrations.
${textImportant('REMEMBER: This only affects the current DB connected to your local Prisma Client. If you have multiple DBs, you will need to run this command for each one.')}
The command that will be run is:
${textImportant(PrismatoKnexSQL)}
---
Do you wish to proceed?`,
`This means that knex won't know about the migrations that Prisma has already applied. If you've got issues with knex, check how to fill the knex_migrations table with the migrations that Prisma has already applied.`,
);
if (!continues) return;

console.log(
`> About to sync Knex's migration-tracking table with Prisma's migration table`,
);
const prisma = new PrismaClient();
let prisma;
try {
const baseDir = getBaseDirectory();
const localPrismaClientDep = await import(
path.resolve(baseDir, 'node_modules', '@prisma/client/default.js')
);
if (!localPrismaClientDep && localPrismaClientDep.PrismaClient) {
errorLog('Prisma Client not found in the project');
return;
}
prisma = new localPrismaClientDep.PrismaClient();
} catch (error) {
console.error(error);
throw new Error(
`Couldn't load the Prisma Client. Make sure you have it installed in your project. Error: ${error.message}`,
);
}

try {
await prisma.$connect();
Expand Down
5 changes: 3 additions & 2 deletions src/setup/pre-check.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,11 @@ async function checkPrismaSchema(baseDir, prismaFolderPath = 'prisma') {
prismaFolderPath,
'schema.prisma',
);
console.log('> Searching for Prisma schema at:', prismaSchemaPath);
const exists = await prismaSchemaExists(prismaSchemaPath);
if (!exists) {
errorLog(
`Prisma schema not found at (${prismaSchemaPath}) - First set Prisma up, then run this script again`,
`> Prisma schema not found at (${prismaSchemaPath}) - First set Prisma up, then run this script again. Are you running this in the folder containing the Prisma folder?`,
);

process.exit(1);
Expand All @@ -39,7 +40,7 @@ async function checkPrismaSchema(baseDir, prismaFolderPath = 'prisma') {

if (!prismaHasKnexModels) {
warningLog(
`Prisma schema found at (${prismaSchemaPath}), but it doesn't have the knex models. I'll run the setup script to add them`,
`> Prisma schema found at (${prismaSchemaPath}), but it doesn't have the knex models. I'll run the setup script to add them`,
);

return true;
Expand Down
2 changes: 1 addition & 1 deletion src/setup/textStyles.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const textExtra = chalk.italic.cyan;
export const successLog = (message, ...args) =>
console.log(textSuccess(message), ...args);
export const errorLog = (message, ...args) =>
console.log(textError(message), ...args);
console.error(textError(message), ...args);
export const warningLog = (message, ...args) =>
console.log(textWarning(message), ...args);

Expand Down
Loading

0 comments on commit 02fc369

Please sign in to comment.