kysely-org / kysely

A type-safe typescript SQL query builder
https://kysely.dev
MIT License
10.33k stars 262 forks source link

Migrations Generator Feature #414

Closed kirylan closed 1 year ago

kirylan commented 1 year ago

Would that make sense to introduce the most basic cli migrations generator? Currently I have to use this following little script to achieve it. I think it self-explains what I mean but basically something that will allow not crating migrations by hand.

import fs from "fs-extra";
import path from "path";
import { fileURLToPath } from "url";
import { dirname } from "path";

// Get the current folder path
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Get the migration name from the command line arguments
const migrationName = process.argv[2];

if (!migrationName) {
  console.error("Please provide a migration name.");
  process.exit(1);
}

const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
const migrationFilename = `${timestamp}_${migrationName}.ts`;
const migrationsDir = path.join(__dirname, "migrations");
const migrationPath = path.join(migrationsDir, migrationFilename);

const template = `
import { Kysely } from "kysely";

export async function up(db: Kysely<any>) {
  // TODO: Implement the up migration
}

export async function down(db: Kysely<any>) {
  // TODO: Implement the down migration
}
`;

(async () => {
  try {
    await fs.ensureDir(migrationsDir);
    await fs.writeFile(migrationPath, template.trim() + "\n");
    console.log(`Migration file created: ${migrationPath}`);
  } catch (error) {
    console.error("Error creating migration file:", error);
    process.exit(1);
  }
})();
koskimas commented 1 year ago

This would add a dependency to node. Any CLI added to kysely must be 100% dependency free and runtime agnostic. That's why a separate package makes more sense.

luxaritas commented 1 year ago

Is there any reason why kysely shouldn't maintain a first-party CLI that can handle migration generation, even if it is a separate package? Many other similar tools seem to provide this

koskimas commented 1 year ago

Feel free to write one 😄

acro5piano commented 1 year ago

I created a thin CLI command to generate migration file. It works like a library instead of an executable CLI, but reduces lots of boilerplate code.

https://github.com/acro5piano/kysely-migration-cli

Hope it helps