diff --git a/README.md b/README.md index c319209..d690518 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,19 @@ This way, you get the ORM and the auto generation of DDL SQL from Prisma, while You can use Prisma to generate the migration SQL, but you never run the migrations with Prisma. Instead, from then on, the prisma-generated SQL DDL gets added into Knex migrations. +## Setup +1. **First, install the dependencies**: `npm install knex dotenv` + > Note: You can use other package managers, like yarn or pnpm. +2. **Run the setup script**: `npx prisma-migration-migrator` + This script will: + - Create a `knexfile.mjs` in the root of your project. + - Add the necessary tables to the prisma schema to ignore the knex migration history tables. + - Add a `create-migration` script to your `package.json` that will create a prisma migration and then convert it to a knex migration (the new flow of migration generation). + - Run the script to convert the existing prisma migrations to knex migrations for the first time. +3. **Run the script**: `npx prisma-migration-migrator` + This script will convert all the existing prisma migrations to knex migrations, and sync the knex migration history with the prisma migration history. This way, Prisma's migration history will be preserved when running knex migrations. + + ## Usage (after setting it up): You can do 2 things: diff --git a/package-lock.json b/package-lock.json index 87ccaef..d41424f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,12 +11,12 @@ "dependencies": { "chalk": "^5.4.1", "inquirer": "^12.3.0", + "prisma-diff-to-knex-migration": "^1.0.2", "sql-query-identifier": "^2.7.0" }, "bin": { "prisma-diff-to-knex": "dist/prismaDiffToKnexMigration.js", - "prisma-migration-migrator": "dist/index.js", - "prisma-to-knex-setup": "dist/setup.mjs" + "prisma-migration-migrator": "dist/index.js" }, "devDependencies": { "@eslint/eslintrc": "^3.2.0", @@ -2428,6 +2428,18 @@ "fsevents": "2.3.3" } }, + "node_modules/prisma-diff-to-knex-migration": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/prisma-diff-to-knex-migration/-/prisma-diff-to-knex-migration-1.0.2.tgz", + "integrity": "sha512-SBdlbWegEw0Rn4sAOY70KDRgPXLUMM5L+J0Qy+nuMMClWsTnXEX/OpZ20Y5QNv5JAXQUXaSy5G+uABDAwTqhrg==", + "license": "MIT", + "dependencies": { + "sql-query-identifier": "^2.8.0" + }, + "bin": { + "prisma-diff-to-knex-migration": "dist/cli.js" + } + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", diff --git a/package.json b/package.json index eb5e139..be4291b 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "dependencies": { "chalk": "^5.4.1", "inquirer": "^12.3.0", + "prisma-diff-to-knex-migration": "^1.0.2", "sql-query-identifier": "^2.7.0" }, "devDependencies": { diff --git a/src/index.ts b/src/index.ts index 6e993f0..ba3cd90 100644 --- a/src/index.ts +++ b/src/index.ts @@ -46,7 +46,3 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) { export { migrator }; export type { MigratorParameters as ConvertPrismaMigrationsToKnexMigrationsParameters }; -export { - knexFilePrismaAdapter, - KnexMigrationSourcePrismaStyle, -} from './knexfilePrismaAdapter/index.mjs'; diff --git a/src/knexMigrationWriter/knexMigrationsWriter.ts b/src/knexMigrationWriter/knexMigrationsWriter.ts deleted file mode 100644 index 1804518..0000000 --- a/src/knexMigrationWriter/knexMigrationsWriter.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { identify } from 'sql-query-identifier'; -import type { IdentifyResult } from 'sql-query-identifier/lib/defines.js'; -import { writeFile } from 'node:fs/promises'; - -const knexMigrationBaseContent = `/** - * @param { import("knex").Knex } knex - * @returns { Promise } - */ -export async function up(knex) { - // Add your up migration SQL here -} - -/** - * @param { import("knex").Knex } knex - * @returns { Promise } - */ -export async function down(knex) { - // Add your down migration SQL here -} -` as const; - -export function generateKnexMigration(rawSql: string = ''): string { - const parsedSQL: IdentifyResult[] = identify(rawSql); - if (!parsedSQL.length) return knexMigrationBaseContent; - - const sentences = parsedSQL - .map( - (parsed) => `await knex.raw(\` -${parsed.text.replace(/`/g, '\\`')} -\`);`, - ) - .join('\n\n '); - - return knexMigrationBaseContent.replace( - '// Add your up migration SQL here', - sentences, - ); -} - -/** - * Identifies the SQL queries and writes the knex migration file, in the final migration path - * @param {MigrationData} prismaMigration - The migration data - */ -export async function knexMigrationWriter( - prismaGeneratedSql: string, - filePath: string, -): Promise { - const knexMigration = generateKnexMigration(prismaGeneratedSql); - await writeFile(filePath, knexMigration); - return knexMigration; -} diff --git a/src/knexMigrationWriter/prismaSchemaSqlDiffGen.ts b/src/knexMigrationWriter/prismaSchemaSqlDiffGen.ts deleted file mode 100644 index fa9f4a2..0000000 --- a/src/knexMigrationWriter/prismaSchemaSqlDiffGen.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { exec } from 'child_process'; -import { promisify } from 'util'; - -const execPromise = promisify(exec); - -export async function buildSqlFromPrismaSchema( - schemaPath: string = './prisma/schema.prisma', -) { - const script = `npx prisma migrate diff --from-schema-datasource ${schemaPath} --to-schema-datamodel ${schemaPath} --script`; - const { stderr: prismaStderr, stdout: prismaStdout } = - await execPromise(script); - - if (prismaStderr) { - console.error('> Error fetching SQL from Prisma:', prismaStderr); - return; - } - - return prismaStdout; -} diff --git a/src/knexfilePrismaAdapter/index.mjs b/src/knexfilePrismaAdapter/index.mjs deleted file mode 100644 index edb9a2b..0000000 --- a/src/knexfilePrismaAdapter/index.mjs +++ /dev/null @@ -1,46 +0,0 @@ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import { KnexMigrationSourcePrismaStyle } from './knexMigrationSourcePrismaStyle.mjs'; -import path from 'node:path'; - -/** - * ATTENTION: ONLY NECESSARY IF YOU WANT TO CO-LOCATE KNEX MIGRATIONS WITH PRISMA MIGRATIONS (put them in the same folder structure) - * IF YOU PLAN TO LEAVE THE MIGRATIONS IN A SEPARATE FOLDER, YOU DON'T NEED THIS AT ALL, JUST USE KNEX NORMALLY - * - * This function adapts the knexfile configuration object to use the PrismaFolderShapedMigrationSource. - * It's what it allows us to pick up the migrations from the prisma/migrations folder (if you decide to co-locate migrations with Prisma) - * It also allows the migrator to pick up where to put the migrated migrations. - * - * The only thing that gets modified is the migrations object (https://github.com/knex/knex/blob/176151d8048b2a7feeb89a3d649a5580786d4f4e/types/index.d.ts#L3139) - * The rest of the configuration object is passed to the knex instance. - * - * If you have different environments (development/production/etc), you should be able to call this function for each of them. - @type {import('knex').Knex.Config} knexfileConfig - @returns {import('knex').Knex.Config} - */ -export function knexFilePrismaAdapter(knexfileConfig) { - const { - directory, - sortDirsSeparately: _, - loadExtensions: __, - extension: ___, - ...otherMigrationsConfigs - } = knexfileConfig?.migrations || {}; - // Knex resets the migrationSource if any FS related config is set, so we need to remove them from the config object - // the rest of the config object is passed as-is to the knex instance - - const migrationsBaseDirectory = directory - ? path.join(process.cwd(), directory) - : path.join(process.cwd(), 'prisma', 'migrations'); // default to ./prisma/migrations - - return { - ...knexfileConfig, - migrations: { - ...otherMigrationsConfigs, - migrationSource: new KnexMigrationSourcePrismaStyle({ - migrationsBaseDirectory, - }), - }, - }; -} - -export { KnexMigrationSourcePrismaStyle }; diff --git a/src/knexfilePrismaAdapter/knexMigrationSourcePrismaStyle.mjs b/src/knexfilePrismaAdapter/knexMigrationSourcePrismaStyle.mjs deleted file mode 100644 index 962e8d5..0000000 --- a/src/knexfilePrismaAdapter/knexMigrationSourcePrismaStyle.mjs +++ /dev/null @@ -1,47 +0,0 @@ -import { access, readdir } from 'fs/promises'; -import path from 'node:path'; - -/** - * This migration source is designed to pick up Migration files arranged in folder, Prisma-style. - */ -export class KnexMigrationSourcePrismaStyle { - migrationsBaseDirectory; - - constructor({ migrationsBaseDirectory }) { - this.migrationsBaseDirectory = migrationsBaseDirectory; - } - - async getMigrations() { - const migrationSubDirectories = await readdir( - this.migrationsBaseDirectory, - { withFileTypes: true }, - ).then((entries) => entries.filter((entry) => entry.isDirectory())); - - const availableMigrations = await Promise.all( - migrationSubDirectories.map(({ name }) => { - const migrationPath = path.join( - this.migrationsBaseDirectory, - name, - 'migration.mjs', - ); - - return access(migrationPath) - .then(() => ({ - name, - migrationPath, - })) - .catch(() => null); - }), - ).then((migrations) => migrations.filter(Boolean)); - - return availableMigrations; - } - - getMigrationName(migration) { - return migration.name; - } - - async getMigration(migration) { - return import(migration.migrationPath); - } -} diff --git a/src/migrator/directories.ts b/src/migrator/directories.ts index c3ebd33..3dcb54a 100644 --- a/src/migrator/directories.ts +++ b/src/migrator/directories.ts @@ -4,13 +4,20 @@ import path from 'node:path'; import type { MigratorParameters } from './types.js'; import { findKnexfile } from './knexfileFinder.js'; +function getInputDirectory( + params: MigratorParameters, + baseDir: string, +): string { + return path.join( + path.resolve(baseDir, params?.prismaFolderPath || 'prisma'), + 'migrations', + ); +} + /** - * ONLY USED for standalone migrations. - * Get the migrations directory from the Knex configuration (`knexfile`) or the `knexfilePath` parameter - * - * For co-located migrations, the directory is the same as the Prisma migrations directory + * Gets the migrations directory from the Knex configuration (`knexfile`) or the `knexfilePath` parameter */ -async function getKnexStandaloneMigrationsDirectory( +async function getOutputDirectory( params: MigratorParameters, baseDir: string, ): Promise { @@ -48,7 +55,8 @@ async function getKnexStandaloneMigrationsDirectory( if (!migrationsDir) { console.error( `Migrations property not found in the Knex configuration. - BEWARE: You need to specify the migrations extension in the Knex configuration for mjs files. Maybe use the setup script included in this package?. + BEWARE: You need to specify the migrations extension in the Knex configuration for mjs files. + Maybe use the setup script included in this package? (npx prisma-migration-migrator --setup). Otherwise, check the knexfile of this library for a working example. Using known default: /migrations`, ); @@ -75,35 +83,22 @@ export function getBaseDirectory() { export async function resolveMigrationDirectories(params?: MigratorParameters) { const baseDir = getBaseDirectory(); - let prismaMigrationsDir, knexMigrationsDir; try { - prismaMigrationsDir = path.join( - path.resolve(baseDir, params?.prismaFolderPath || 'prisma'), - 'migrations', - ); + const prismaMigrationsDir = getInputDirectory(params, baseDir); console.log(`> > Converting Prisma migrations from ${prismaMigrationsDir}`); - if (!params?.colocate) { - knexMigrationsDir = await getKnexStandaloneMigrationsDirectory( - params, - baseDir, - ); - if (!knexMigrationsDir) { - throw new Error('Knex migrations directory not found'); - } - console.log( - `> > Will locate converted migrations in the directory: ${knexMigrationsDir}`, - ); - await mkdir(knexMigrationsDir, { recursive: true }); - } else { - console.log( - `> > Will co-locate converted migrations with Prisma migrations in the same directory`, - ); + const knexMigrationsDir = await getOutputDirectory(params, baseDir); + if (!knexMigrationsDir) { + throw new Error('Knex migrations directory not found'); } + console.log( + `> > Will locate converted migrations in the directory: ${knexMigrationsDir}`, + ); + await mkdir(knexMigrationsDir, { recursive: true }); + + return { prismaMigrationsDir, knexMigrationsDir }; } catch (err) { console.error('> Error resolving migration directories:', err); throw err; } - - return { prismaMigrationsDir, knexMigrationsDir }; } diff --git a/src/migrator/index.ts b/src/migrator/index.ts index d0f11df..ac6daea 100644 --- a/src/migrator/index.ts +++ b/src/migrator/index.ts @@ -6,5 +6,5 @@ import type { MigratorParameters } from './types.js'; export async function migrator(params?: MigratorParameters): Promise { const migrations = await getMigrationsToMigrate(params); await knexMigrationsWriter(migrations); - await syncMigrationTables(params); + await syncMigrationTables(); } diff --git a/src/migrator/knexMigrationsWriter.ts b/src/migrator/knexMigrationsWriter.ts index eb3ff8f..0c8fdec 100644 --- a/src/migrator/knexMigrationsWriter.ts +++ b/src/migrator/knexMigrationsWriter.ts @@ -1,4 +1,4 @@ -import { knexMigrationWriter } from '../knexMigrationWriter/knexMigrationsWriter.js'; +import { knexMigrationWriter } from 'prisma-diff-to-knex-migration'; import type { MigrationData } from './types.js'; export async function knexMigrationsWriter( diff --git a/src/migrator/prismaMigrationsFetcher.ts b/src/migrator/prismaMigrationsFetcher.ts index 7a23859..1512ef1 100644 --- a/src/migrator/prismaMigrationsFetcher.ts +++ b/src/migrator/prismaMigrationsFetcher.ts @@ -3,6 +3,7 @@ import { createHash } from 'node:crypto'; import path from 'node:path'; import type { MigrationData, MigratorParameters } from './types.js'; import { resolveMigrationDirectories } from './directories.js'; +import { identify } from 'sql-query-identifier'; export function calculateChecksum(data: string): string { return createHash('sha256').update(data, 'utf8').digest('hex'); @@ -33,9 +34,10 @@ export async function getMigrationsToMigrate( 'migration.sql', ); - const finalMigrationPath = params?.colocate - ? path.join(prismaMigrationsDir, name, 'migration.mjs') - : path.join(knexMigrationsDir, `${name}.mjs`); + const finalMigrationPath = path.join( + knexMigrationsDir, + `${name}.mjs`, + ); const alreadyExists = await access(finalMigrationPath) .then(() => true) @@ -70,7 +72,7 @@ export async function getMigrationsToMigrate( name, baseSqlPath, finalMigrationPath, - sql, + sql: identify(sql), checksum: calculateChecksum(sql), })), ), diff --git a/src/migrator/syncMigrationTables.ts b/src/migrator/syncMigrationTables.ts index ab0b604..071a9da 100644 --- a/src/migrator/syncMigrationTables.ts +++ b/src/migrator/syncMigrationTables.ts @@ -1,6 +1,5 @@ import { PrismaClient } from '@prisma/client'; import { knexMigrationsLockSql, knexMigrationsSQl } from './constants.js'; -import type { MigratorParameters } from './types.js'; async function checkIfTableIsPresent( prisma: PrismaClient, @@ -34,11 +33,10 @@ async function createKnexMigrationsTable(prisma: PrismaClient): Promise { async function syncKnexAndPrismaMigrations( prisma: PrismaClient, - params: MigratorParameters, ): Promise { const res = await prisma.$executeRawUnsafe(` INSERT INTO knex_migrations (name, batch, migration_time) - SELECT migration_name ${params.colocate ? '' : `|| '.mjs'`}, 1, finished_at + SELECT migration_name || '.mjs', 1, finished_at FROM _prisma_migrations WHERE migration_name NOT IN ( SELECT name @@ -48,9 +46,7 @@ async function syncKnexAndPrismaMigrations( console.log(`> > Synced ${res} migrations from Prisma to Knex`); } -export async function syncMigrationTables( - params: MigratorParameters, -): Promise { +export async function syncMigrationTables(): Promise { console.log( `> About to sync Knex's migration-tracking table with Prisma's migration table`, ); @@ -85,7 +81,7 @@ export async function syncMigrationTables( console.log(`> Knex's migration-tracking table is present`); } - await syncKnexAndPrismaMigrations(prisma, params); + await syncKnexAndPrismaMigrations(prisma); console.log( `> Successfully synced Knex's migration-tracking table with Prisma's migration table`, ); diff --git a/src/migrator/types.ts b/src/migrator/types.ts index 804cdee..c8ebb6b 100644 --- a/src/migrator/types.ts +++ b/src/migrator/types.ts @@ -1,8 +1,9 @@ +import type { IdentifyResult } from './types.js'; + export type { IdentifyResult } from 'sql-query-identifier/lib/defines.js'; export type MigratorParameters = { prismaFolderPath?: string; - colocate?: boolean; knexfilePath?: string; // not strictly necessary, will try to find it. It's the fallback. knexMigrationsDir?: string; // not necessary, it's the fallback of the fallback @@ -13,6 +14,6 @@ export type MigrationData = { name: string; baseSqlPath: string; finalMigrationPath: string; - sql: string; + sql: IdentifyResult[]; checksum: string; }; diff --git a/src/migrator/unusedMarkPrismaMigrationAs.ts b/src/migrator/unusedMarkPrismaMigrationAs.ts deleted file mode 100644 index 1f36b22..0000000 --- a/src/migrator/unusedMarkPrismaMigrationAs.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { exec } from 'node:child_process'; -import util from 'util'; - -const execPromise = util.promisify(exec); - -/** - * @typedef {Object} MarkPrismaMigrationAsParams - * @property {string} [databaseUrl] - * @property {string} migrationName - * @property {'applied' | 'rolled-back'} action - * @property {string} [schema] - */ - -/** - * Marks a Prisma migration as applied or rolled-back. - * @param {MarkPrismaMigrationAsParams} params - The parameters for marking the migration. - */ -export async function markPrismaMigrationAs({ - databaseUrl, - migrationName, - action, - schema, -}) { - if (!migrationName) throw new Error('You must provide a migration name'); - const env = { ...process.env }; - let commandToRun = 'npx prisma migrate resolve'; - if (databaseUrl) env.DATABASE_URL = databaseUrl; - commandToRun += ` --${action} ${migrationName}`; - if (schema) commandToRun += ` --schema=${schema}`; - - const { stdout, stderr } = await execPromise(commandToRun, { env }); - console.log(` > markPrismaMigrationAs ${action} ${migrationName}: `, stdout); - - if (stderr) { - throw new Error(stderr); - } -} - -// Example usage: -// await markPrismaMigrationAs({ -// action: 'applied', -// migrationName: '20250112145436_add_knex_models', -// }); diff --git a/src/prismaDiffToKnexMigration.ts b/src/prismaDiffToKnexMigration.ts index 4db79e3..390fe33 100644 --- a/src/prismaDiffToKnexMigration.ts +++ b/src/prismaDiffToKnexMigration.ts @@ -1,5 +1,7 @@ -import { buildSqlFromPrismaSchema } from './knexMigrationWriter/prismaSchemaSqlDiffGen.js'; -import { knexMigrationWriter } from './knexMigrationWriter/knexMigrationsWriter.js'; +import { + buildSqlFromPrismaSchema, + knexMigrationWriter, +} from 'prisma-diff-to-knex-migration'; export async function prismaDiffToKnexMigration(params: { output: 'console' | 'file'; diff --git a/src/setup/knexFileGen.mjs b/src/setup/knexFileGen.mjs index 886e49d..7e78d24 100644 --- a/src/setup/knexFileGen.mjs +++ b/src/setup/knexFileGen.mjs @@ -9,7 +9,7 @@ import { textWarning, } from './textStyles.mjs'; -const standaloneTemplate = ` +const template = ` // Knex configuration object const config = { client: 'pg', @@ -24,33 +24,14 @@ const config = { export default config; `; -const coLocatedKnexfileTemplate = ` -import { knexFilePrismaAdapter } from 'prisma-migration-migrator'; - -// Knex configuration object -const config = knexFilePrismaAdapter({ - client: 'pg', - connection: process.env.DATABASE_URL, - migrations: { - directory: 'prisma/migrations', - }, -}); - -export default config; -`; - const dotenvTemplate = ` import dotenv from 'dotenv'; dotenv.config(); `; -function buildKnexfileContent(addDotenv = true, colocated = false) { - let knexfileContent = colocated - ? coLocatedKnexfileTemplate - : standaloneTemplate; - +function buildKnexfileContent(addDotenv = true) { if (addDotenv) - return knexfileContent.replace( + return template.replace( '// Knex configuration object', '// Knex configuration object\n' + dotenvTemplate, ); @@ -71,7 +52,7 @@ If you've already created a knexfile.mjs file, this step will overwrite it. Do y ); if (!continues) return; - const { dotenv, colocated } = await inquirer.prompt([ + const { dotenv } = await inquirer.prompt([ { type: 'list', name: 'dotenv', @@ -79,18 +60,9 @@ If you've already created a knexfile.mjs file, this step will overwrite it. Do y ${textWarning(`If you don't want to add it, it's fine, as long as you set the connection property correctly.`)}`, choices: ['Yes', 'No'], }, - { - type: 'list', - name: 'colocated', - message: `Do you wish for the migrations to be co-located with the Prisma migrations?`, - choices: ['No', 'Yes'], - }, ]); - await fs.writeFile( - 'knexfile.mjs', - buildKnexfileContent(dotenv === 'Yes', colocated === 'Yes'), - ); + await fs.writeFile('knexfile.mjs', buildKnexfileContent(dotenv === 'Yes')); successLog( '> knexfile.mjs created successfully on base directory. Please review it.', ); diff --git a/src/tests/helpers/types.ts b/src/tests/helpers/types.ts index 94beb74..e2c7dd2 100644 --- a/src/tests/helpers/types.ts +++ b/src/tests/helpers/types.ts @@ -1,5 +1,4 @@ export type TestParameters = { - colocate?: boolean; dbUrl: string; silent?: boolean; skipInitialPrismaMigrationRun?: boolean; diff --git a/src/tests/helpers/util-cleanup.ts b/src/tests/helpers/util-cleanup.ts index 13753eb..e3eccfe 100644 --- a/src/tests/helpers/util-cleanup.ts +++ b/src/tests/helpers/util-cleanup.ts @@ -1,28 +1,14 @@ import { existsSync, rmSync } from 'node:fs'; -import { readdir, rm, unlink, writeFile } from 'node:fs/promises'; -import path from 'node:path'; +import { writeFile } from 'node:fs/promises'; import pg from 'pg'; import { baseDBUrl, knexMigrationsDir, - prismaDir, prismaSchemaPath, testDbName, } from './constants.js'; -function isTestProtectedFolder(entry: string) { - const protectedFolders = [ - 'init', - 'new_delete_field', - 'prisma', - 'migrations', - 'add_knex', - ]; - - return protectedFolders.some((folderName) => entry.includes(folderName)); -} - async function resetDatabase(databaseName: string, silent = true) { const client = new pg.Client({ connectionString: baseDBUrl + '/postgres' }); @@ -51,29 +37,6 @@ async function resetDatabase(databaseName: string, silent = true) { await client.end(); } } -async function removeMigrationFiles(dir: string, silent = true) { - if (!existsSync(dir)) - throw new Error( - `RemoveMigrationFiles - Expected to exist directory (${dir}) does not exist .`, - ); - - const entries = await readdir(dir, { withFileTypes: true }); - for (const entry of entries) { - const fullPath = path.join(dir, entry.name); - - if (entry.isDirectory()) { - if (!isTestProtectedFolder(entry.name)) { - await rm(fullPath, { recursive: true }); - !silent && console.log(`Removed folder: ${entry.name}`); - } else { - await removeMigrationFiles(fullPath); - } - } else if (entry.isFile() && entry.name === 'migration.mjs') { - await unlink(fullPath); - !silent && console.log(`Removed file: ${fullPath}`); - } - } -} function cleanupMigrationFolder(dir: string, silent = true) { if (existsSync(dir)) { @@ -124,12 +87,8 @@ model knex_migrations_lock { } // Cleanup function -export async function cleanup(colocate: boolean, silent = true) { - if (colocate) { - await removeMigrationFiles(prismaDir, silent); - } else { - cleanupMigrationFolder(knexMigrationsDir, silent); - } +export async function cleanup(silent = true) { + cleanupMigrationFolder(knexMigrationsDir, silent); await resetDatabase(testDbName); diff --git a/src/tests/helpers/util-knex-migrator.ts b/src/tests/helpers/util-knex-migrator.ts index 55ede30..1f95185 100644 --- a/src/tests/helpers/util-knex-migrator.ts +++ b/src/tests/helpers/util-knex-migrator.ts @@ -1,9 +1,8 @@ import Knex from 'knex'; -import { knexFilePrismaAdapter } from '../../knexfilePrismaAdapter/index.mjs'; -export async function runKnexMigrations(databaseUrl, colocate = false) { +export async function runKnexMigrations(databaseUrl) { console.log('T Running Knex Migrations...'); - let config: Knex.Knex.Config = { + const config: Knex.Knex.Config = { client: 'pg', connection: databaseUrl, migrations: { @@ -13,13 +12,6 @@ export async function runKnexMigrations(databaseUrl, colocate = false) { }, }; - if (colocate) { - config = knexFilePrismaAdapter({ - ...config, - migrations: { directory: 'prisma/migrations' }, - }); - } - const knexClient = await Knex(config); const [, appliedMigrations] = await knexClient.migrate.latest(); knexClient.destroy(); diff --git a/src/tests/tests.ts b/src/tests/tests.ts index 75cef78..14c4775 100644 --- a/src/tests/tests.ts +++ b/src/tests/tests.ts @@ -12,24 +12,22 @@ import { migrator } from '../migrator/index.js'; async function test(parameters: TestParameters) { const { dbUrl, - colocate = false, silent = false, skipInitialPrismaMigrationRun = false, } = parameters; console.log(`T Test parameters:`, parameters); - await cleanup(colocate, silent); + await cleanup(silent); !skipInitialPrismaMigrationRun && (await runPrismaMigrations(dbUrl)); console.log('T Conversion started'); await migrator({ - colocate, silent, knexMigrationsDir, }); console.log('T Conversion completed'); - const migrationsByKnex = await runKnexMigrations(dbUrl, colocate); + const migrationsByKnex = await runKnexMigrations(dbUrl); const prismaState = await snapshotDbStructure(dbUrl); const knexState = await snapshotDbStructure(dbUrl); @@ -53,12 +51,6 @@ async function test(parameters: TestParameters) { const acceptanceCases: TestParameters[] = [ { dbUrl }, { dbUrl, skipInitialPrismaMigrationRun: true }, - { dbUrl, colocate: true }, - { - dbUrl, - colocate: true, - skipInitialPrismaMigrationRun: true, - }, ]; async function executeAllTests() {