Skip to content

Commit

Permalink
chore: fomrat and make minor changes
Browse files Browse the repository at this point in the history
  • Loading branch information
ruheni committed Oct 10, 2022
1 parent 4e6d839 commit 61bd9b4
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 21 deletions.
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<div align=center>

<h1>db-diff</h1>

</div>

`db-diff` is a helper library built on top of the [Prisma](https://www.prisma.io/) CLI for auto-generating and versioning customizable database migrations (compatible with [Postgrator](https://www.npmjs.com/package/postgrator)). By default, the library auto-generates both `up` and `down migrations when you run the command.


If you already have an existing Prisma schema in your project, run the following command

```
npx db-diff
```

Optional arguments:

| Option | Arguments | Default | Description |
| :----------------: | :-------: | :----------------------: | :-----------------------------------------------------------------------------------: |
| `--schema` | | `./prisma/schema.prisma` | Path to your Prisma schema file. |
| `--migrations-dir` | | `./migrations` | Path to your migrations directory. If the folder will be created if it doesnn't exist |
| ` --up ` | | | Generate only the `up` migration only |
| `--down` | | | Generate only the `down` migration only |

Example usage:


```bash
npx db-diff --migrations-dir ./src/migrations
```

Generate only the `up` migration:

```bash
npx db-diff --up
```

Generate only the `down` migration:
```bash
npx db-diff --down
```
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ import logger from "./lib/logger";
import generateMigrations from "./lib/migration";
import CLI from "./cli";
import path from "path";

async function main() {
const { migrationsDir, schema, up, down } = CLI();

const normalizedMigrationsDirPath = path.join(process.cwd(), migrationsDir);
const normalizedSchemaPath = path.join(process.cwd(), schema);

if (up) {
await generateMigrations(
normalizedMigrationsDirPath,
Expand Down
1 change: 1 addition & 0 deletions src/lib/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ export default {
error: (message) => log(chalk.red(message)),
info: (message) => log(chalk.yellow(message)),
success: (message) => log(chalk.green(message)),
gray: (message) => log(chalk.gray(message)),
};
45 changes: 24 additions & 21 deletions src/lib/migration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ type MigrationKind = "up" | "down";

async function createMigrationDirectoryIfNotExists(migrationDir: string) {
try {
fs.stat(migrationDir);
await fs.stat(migrationDir);
} catch (error) {
if (error.code === "ENOENT") {
logger.info("Generating migration folder");
logger.info(`Creating your migration folder in ${migrationDir}`);
fs.mkdir(migrationDir);
}
}
Expand Down Expand Up @@ -41,50 +41,53 @@ async function generateMigrations(
) {
await createMigrationDirectoryIfNotExists(migrationDir);

const nextMigrationId = await getNextMigrationId(migrationDir, migrationKind);
const nextMigrationId = await getNextMigrationId(
migrationDir,
migrationKind,
).then((value) => value?.toString().padStart(3, "0"));

switch (migrationKind) {
case "up": {
const { stdout: upMigrationStdout } = await execaCommand(
const { exitCode, stdout } = await execaCommand(
`npx prisma migrate diff \
--from-schema-datasource ${schemaPath} \
--to-schema-datamodel ${schemaPath} \
--script`,
--script \
--exit-code`,
);

if (!upMigrationStdout.includes("empty migration")) {
if (exitCode === 2) {
await fs
.appendFile(
`${migrationDir}/${nextMigrationId}.do.sql`,
upMigrationStdout,
)
.writeFile(`${migrationDir}/${nextMigrationId}.do.sql`, stdout)
.then(() =>
logger.success(`🗳 Generated new ${nextMigrationId} up migration`),
logger.success(
`🗳 Generated ${nextMigrationId}.do.sql up migration`,
),
);
} else {
logger.info("📭 No new up migration was generated.");
logger.gray("📭 No new up migration was generated.");
}
break;
}

case "down": {
const { stdout: downMigrationStdout } = await execaCommand(
const { exitCode, stdout } = await execaCommand(
`npx prisma migrate diff \
--from-schema-datamodel ${schemaPath} \
--to-schema-datasource ${schemaPath} \
--script`,
--script \
--exit-code`,
);
if (!downMigrationStdout.includes("empty migration")) {
if (exitCode === 2) {
await fs
.appendFile(
`${migrationDir}/${nextMigrationId}.undo.sql`,
downMigrationStdout,
)
.appendFile(`${migrationDir}/${nextMigrationId}.undo.sql`, stdout)
.then(() =>
logger.success(`🗳 Generated new ${nextMigrationId} down migration`),
logger.success(
`🗳 Generated new ${nextMigrationId}.undo.sql down migration`,
),
);
} else {
logger.info("📭 No new down migration was generated.");
logger.gray("📭 No new down migration was generated.");
}
break;
}
Expand Down

0 comments on commit 61bd9b4

Please sign in to comment.