Skip to content

Commit

Permalink
reduce scope, remove colocation stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
spersico committed Jan 15, 2025
1 parent 4921361 commit a7326d0
Show file tree
Hide file tree
Showing 21 changed files with 82 additions and 356 deletions.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
16 changes: 14 additions & 2 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
4 changes: 0 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
51 changes: 0 additions & 51 deletions src/knexMigrationWriter/knexMigrationsWriter.ts

This file was deleted.

19 changes: 0 additions & 19 deletions src/knexMigrationWriter/prismaSchemaSqlDiffGen.ts

This file was deleted.

46 changes: 0 additions & 46 deletions src/knexfilePrismaAdapter/index.mjs

This file was deleted.

47 changes: 0 additions & 47 deletions src/knexfilePrismaAdapter/knexMigrationSourcePrismaStyle.mjs

This file was deleted.

53 changes: 24 additions & 29 deletions src/migrator/directories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | null> {
Expand Down Expand Up @@ -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: <project-root>/migrations`,
);
Expand All @@ -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 };
}
2 changes: 1 addition & 1 deletion src/migrator/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ import type { MigratorParameters } from './types.js';
export async function migrator(params?: MigratorParameters): Promise<void> {
const migrations = await getMigrationsToMigrate(params);
await knexMigrationsWriter(migrations);
await syncMigrationTables(params);
await syncMigrationTables();
}
2 changes: 1 addition & 1 deletion src/migrator/knexMigrationsWriter.ts
Original file line number Diff line number Diff line change
@@ -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(
Expand Down
10 changes: 6 additions & 4 deletions src/migrator/prismaMigrationsFetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -70,7 +72,7 @@ export async function getMigrationsToMigrate(
name,
baseSqlPath,
finalMigrationPath,
sql,
sql: identify(sql),
checksum: calculateChecksum(sql),
})),
),
Expand Down
Loading

0 comments on commit a7326d0

Please sign in to comment.