Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

reset command & avoid printing stack for user errs

Roman Pominov0b9feb0c8522
diff --git a/packages/prisma-client/migrations-cli/cli-error.ts b/packages/prisma-client/migrations-cli/cli-error.ts
new file mode 100644
index 0000000000..c5f4d3a163
--- /dev/null
+++ b/packages/prisma-client/migrations-cli/cli-error.ts
@@ -0,0 +1,6 @@
+// A special error that when thrown signals
+// to the CLI that it doesn't need to print the stacktrace.
+//
+// This should be used for the errors caused by user's input or actions
+// as opposed to errors caused by bugs in the code.
+export class CliError extends Error {}
diff --git a/packages/prisma-client/migrations-cli/cli.ts b/packages/prisma-client/migrations-cli/cli.ts
index 7a3014286e..cf97b6ded7 100755
--- a/packages/prisma-client/migrations-cli/cli.ts
+++ b/packages/prisma-client/migrations-cli/cli.ts
@@ -4,12 +4,7 @@ import * as dotenv from "dotenv";
import * as commands from "./commands";
import * as logger from "./logger";
import args from "./args";
-
-const failWith = (message: string) => {
- logger.error(message);
- logger.error("");
- process.exit(1);
-};
+import { CliError } from "./cli-error";
const USAGE = `Usage: migrations <command> [--dev]
@@ -26,84 +21,88 @@ Arguments
`;
const main = async () => {
- if (args.dev) {
- dotenv.config();
- }
-
- const command = args._[0];
+ try {
+ if (args.dev) {
+ dotenv.config();
+ }
- if (command === undefined) {
- logger.info(USAGE);
- return;
- }
+ const command = args._[0];
- if (command === "create-schema") {
- const name = args._[1];
- if (name === undefined) {
- failWith(
- "Missing name for migration.\nUsage: migrations create-schema <name>"
- );
+ if (command === undefined) {
+ logger.info(USAGE);
return;
}
- await commands.createSchema({ name });
- return;
- }
- if (command === "create-data") {
- const name = args._[1];
- if (name === undefined) {
- failWith(
- "Missing name for migration.\nUsage: migrations create-data <name>"
- );
+ if (command === "create-schema") {
+ const name = args._[1];
+ if (name === undefined) {
+ throw new CliError(
+ "Missing name for migration.\nUsage: migrations create-schema <name>"
+ );
+ }
+ await commands.createSchema({ name });
return;
}
- await commands.createData({ name });
- return;
- }
-
- if (command === "migrate") {
- await commands.migrate();
- return;
- }
-
- if (command === "status") {
- await commands.status();
- return;
- }
-
- if (command === "resolve") {
- // @todo: confirmation prompt
- const type = args._[1];
+ if (command === "create-data") {
+ const name = args._[1];
+ if (name === undefined) {
+ throw new CliError(
+ "Missing name for migration.\nUsage: migrations create-data <name>"
+ );
+ }
+ await commands.createData({ name });
+ return;
+ }
- if (type === undefined || (type !== "applied" && type !== "rolled-back")) {
- failWith(
- "Missing type of resolve.\nUsage: migrations resolve <applied|rolled-back> <migration-name>"
- );
+ if (command === "migrate") {
+ await commands.migrate();
return;
}
- const name = args._[2];
- if (name === undefined) {
- failWith(
- "Missing name of migration.\nUsage: migrations resolve <applied|rolled-back> <migration-name>"
- );
+ if (command === "status") {
+ await commands.status();
return;
}
- await commands.resolve({ migrationName: name, resolveAs: type });
- return;
- }
+ if (command === "resolve") {
+ const type = args._[1];
+
+ if (
+ type === undefined ||
+ (type !== "applied" && type !== "rolled-back")
+ ) {
+ throw new CliError(
+ "Missing type of resolve.\nUsage: migrations resolve <applied|rolled-back> <migration-name>"
+ );
+ }
+
+ const name = args._[2];
+ if (name === undefined) {
+ throw new CliError(
+ "Missing name of migration.\nUsage: migrations resolve <applied|rolled-back> <migration-name>"
+ );
+ }
+
+ await commands.resolve({ migrationName: name, resolveAs: type });
+ return;
+ }
- if (command === "reset") {
- // @todo: confirmation prompt
- // @todo: allow only in dev mode
+ if (command === "reset") {
+ await commands.reset();
+ return;
+ }
- // @todo
- throw new Error("Not implemented");
+ throw new CliError(`Unknown command: ${command}`);
+ } catch (error) {
+ if (error instanceof CliError) {
+ logger.error(error.message);
+ logger.error("");
+ process.exit(1);
+ } else {
+ throw error;
+ }
}
-
- failWith(`Unknown command: ${command}`);
};
main();
diff --git a/packages/prisma-client/migrations-cli/commands.ts b/packages/prisma-client/migrations-cli/commands.ts
index e24afbefdd..02a89a3ae7 100644
--- a/packages/prisma-client/migrations-cli/commands.ts
+++ b/packages/prisma-client/migrations-cli/commands.ts
@@ -6,6 +6,7 @@ import * as prismaMigrations from "./prisma-migrations";
import { umzug } from "./umzug";
import * as logger from "./logger";
import args from "./args";
+import { CliError } from "./cli-error";
const templateFilePath = path.join(
prismaMigrations.migrationsDir,
@@ -38,10 +39,12 @@ const confirm = async (
});
};
-const failWith = (message: string) => {
- logger.error(message);
- logger.error("");
- process.exit(1);
+const ensureUserWantiToContinue = async (defaultResult = false) => {
+ const result = await confirm("Continue?", defaultResult);
+ if (result === false) {
+ logger.info("Aborted.");
+ process.exit(0);
+ }
};
const writeFile = (filePath: string, content: string) => {
@@ -103,7 +106,7 @@ const ensureNoFailed = (status: Status) => {
(migration) => migration.state === "failed"
);
if (failed.length > 0) {
- failWith(
+ throw new CliError(
`There are failed migrations:\n${failed
.map((item) => {
let text = ` - ${item.migration.migration_name}`;
@@ -122,7 +125,7 @@ const ensureNoFailed = (status: Status) => {
const ensureNoPending = (status: Status) => {
if (status.pending.length > 0) {
- failWith(
+ throw new CliError(
`There are pending migrations:\n${status.pending
.map((migration) => ` - ${migration.name}`)
.join(
@@ -137,7 +140,7 @@ const ensureLastPending = async (migrationsName: string) => {
const last = pending[pending.length - 1];
if (last === undefined || last.name !== migrationsName) {
- failWith(
+ throw new CliError(
"The migrations you've created did not appear as the last pending migration. This isn't supposed to happen. Please investigate / report this issue."
);
}
@@ -234,29 +237,7 @@ ${schemaContent}`;
logger.info("");
};
-export const migrate = async () => {
- const status = await getStatus();
-
- ensureNoFailed(status);
-
- if (status.pending.length === 0) {
- logger.info("No pending migrations\n");
- process.exit(0);
- }
-
- logger.info("You're about to apply the following migration(s):");
- logger.info("");
-
- for (const migration of status.pending) {
- logger.info(` - ${migration.name}`);
- }
-
- logger.info("");
-
- if ((await confirm("Continue?", true)) === false) {
- process.exit(0);
- }
-
+const up = async () => {
let locker: FileLocker | undefined;
if (args.dev) {
locker = new FileLocker({ path: lockfilePath });
@@ -266,11 +247,11 @@ export const migrate = async () => {
try {
await locker.getLock();
} catch (e) {
- failWith(
+ throw new CliError(
`Could not acquire lock!
This means that another process is already running migrations.
If you're sure no other process is running, please delete the lockfile:
- ${lockfilePath}`
+ $ rm ${lockfilePath}`
);
}
}
@@ -295,6 +276,28 @@ If you're sure no other process is running, please delete the lockfile:
}
};
+export const migrate = async () => {
+ const status = await getStatus();
+
+ ensureNoFailed(status);
+
+ if (status.pending.length === 0) {
+ logger.info("No pending migrations\n");
+ process.exit(0);
+ }
+
+ logger.info("You're about to apply the following migration(s):");
+ logger.info("");
+ for (const migration of status.pending) {
+ logger.info(` - ${migration.name}`);
+ }
+ logger.info("");
+
+ await ensureUserWantiToContinue(true);
+
+ await up();
+};
+
export const status = async () => {
const status = await getStatus();
@@ -341,7 +344,7 @@ export const resolve = async ({
({ migration }) => migration.migration_name === migrationName
) === false
) {
- failWith(
+ throw new CliError(
`Migration ${migrationName} is not failed. You can resolve only a failed migration.`
);
}
@@ -354,9 +357,7 @@ export const resolve = async ({
);
logger.info("");
- if ((await confirm(`Continue?`)) === false) {
- process.exit(0);
- }
+ await ensureUserWantiToContinue();
if (resolveAs === "applied") {
await prismaMigrations.setApplied(migrationName);
@@ -369,3 +370,24 @@ export const resolve = async ({
logger.info(`Resolved ${migrationName} as rolled back`);
logger.info("");
};
+
+export const reset = async () => {
+ // just to make it read the migrations folder
+ // and fail early if something is wrong with the migration files
+ await getStatus();
+
+ if (args.dev === false) {
+ throw new CliError(
+ "This command is only available in dev mode. Try again with --dev."
+ );
+ }
+
+ logger.info("You're about to DELETE ALL INFORMATION from the database,");
+ logger.info("and run all migrations from scratch!");
+ logger.info("");
+
+ await ensureUserWantiToContinue();
+
+ await prismaMigrations.resetDatabase();
+ await up();
+};
diff --git a/packages/prisma-client/migrations-cli/prisma-migrations.ts b/packages/prisma-client/migrations-cli/prisma-migrations.ts
index 74b1945267..8ceba95120 100644
--- a/packages/prisma-client/migrations-cli/prisma-migrations.ts
+++ b/packages/prisma-client/migrations-cli/prisma-migrations.ts
@@ -7,22 +7,42 @@ import path from "node:path";
import fs from "node:fs";
import { createHash } from "node:crypto";
import { prisma } from "../src";
+import { CliError } from "./cli-error";
export const prismaDir = path.resolve(__dirname, "..", "prisma");
export const schemaFilePath = path.join(prismaDir, "schema.prisma");
export const migrationsDir = path.join(prismaDir, "migrations");
+const getDatabaseSchemaName = () => {
+ // This should return something like prisma.datasource.schema.
+ // Unfortunately, Prisma doesn't expose this information.
+ //
+ // To do this properly manually we'd need to:
+ // 1. Parse the schema file to read `datasource` definition
+ // 2. Extract the connection url from the datasource
+ // 3. Read `?schema` parameter from the connection url as defined here:
+ // https://www.prisma.io/docs/concepts/database-connectors/postgresql#connection-url
+ //
+ // 1 and 2 is not trivial, so we assume that DATABASE_URL env variable is used, and jump to 3.
+ // But we'll need to find a better way if this becomes a library.
+
+ const defaultSchemaName = "public";
+
+ const urlString = process.env.DATABASE_URL;
+ if (urlString === undefined || urlString.trim() === "") {
+ return defaultSchemaName;
+ }
+
+ const url = new URL(urlString);
+ return url.searchParams.get("schema") || defaultSchemaName;
+};
+
export const getMigrationFilePath = (
migrationName: string,
type: "ts" | "sql"
) => path.join(migrationsDir, migrationName, `migration.${type}`);
-let tableExists = false;
export const ensureMigrationTable = async () => {
- if (tableExists) {
- return;
- }
-
// https://github.com/prisma/prisma-engines/blob/4.3.0/migration-engine/ARCHITECTURE.md#the-_prisma_migrations-table
// https://github.com/prisma/prisma-engines/blob/88f6ab88e559ef52ab26bc98f1da15200e0c25b4/migration-engine/connectors/sql-migration-connector/src/flavour/postgres.rs#L211-L226
await prisma.$executeRaw`CREATE TABLE IF NOT EXISTS _prisma_migrations (
@@ -35,8 +55,6 @@ export const ensureMigrationTable = async () => {
started_at TIMESTAMPTZ NOT NULL DEFAULT now(),
applied_steps_count INTEGER NOT NULL DEFAULT 0
)`;
-
- tableExists = true;
};
// Fields' descriptions are quoted from ARCHITECTURE.md
@@ -225,6 +243,15 @@ export const generateMigrationName = (baseName: string) => {
return `${prefix}_${baseName}`.slice(0, 254);
};
+export const resetDatabase = async () => {
+ const schemaName = getDatabaseSchemaName();
+
+ // https://github.com/prisma/prisma-engines/blob/b92d74444c1c0298714e9b140a85dd714b8dc7c4/migration-engine/connectors/sql-migration-connector/src/flavour/postgres.rs#L267-L278
+ // @todo: need to use something like pg-escape for schemaName, not super urgent as this is only used in development
+ await prisma.$executeRawUnsafe(`DROP SCHEMA "${schemaName}" CASCADE`);
+ await prisma.$executeRawUnsafe(`CREATE SCHEMA "${schemaName}"`);
+};
+
// https://www.prisma.io/docs/reference/api-reference/command-reference#migrate-diff
export const cliDiff = () => {
return execaSync("prisma", [
@@ -264,7 +291,7 @@ export const generateMigrationClient = (migrationName: string) => {
if (fs.existsSync(schemaPath) === false) {
const tsFilePath = getMigrationFilePath(migrationName, "ts");
if (fs.existsSync(tsFilePath)) {
- throw new Error(
+ throw new CliError(
`Can't generate client for ${migrationName} because ${migrationName}/schema.prisma is missing`
);
}
diff --git a/packages/prisma-client/migrations-cli/umzug.ts b/packages/prisma-client/migrations-cli/umzug.ts
index a9923ed6ec..0d0f4666db 100755
--- a/packages/prisma-client/migrations-cli/umzug.ts
+++ b/packages/prisma-client/migrations-cli/umzug.ts
@@ -2,6 +2,7 @@ import { Umzug } from "umzug";
import fs from "node:fs";
import * as prismaMigrations from "./prisma-migrations";
import * as logger from "./logger";
+import { CliError } from "./cli-error";
export const umzug = new Umzug({
migrations: {
@@ -39,7 +40,7 @@ export const umzug = new Umzug({
const migration = require(tsFilePath);
if (typeof migration.default !== "function") {
- throw new Error(
+ throw new CliError(
`Migration file's ${tsFilePath} default export must be a function`
);
}
@@ -50,7 +51,7 @@ export const umzug = new Umzug({
};
}
- throw new Error(
+ throw new CliError(
`Couldn't find a migration.ts or migration.sql file in migrations/${params.name}`
);
},