"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var chunk_VXCRYJ2J_exports = {};
__export(chunk_VXCRYJ2J_exports, {
  DbPush: () => DbPush,
  init_DbPush: () => init_DbPush
});
module.exports = __toCommonJS(chunk_VXCRYJ2J_exports);
var import_chunk_BOP7PHOB = require("./chunk-BOP7PHOB.js");
var import_chunk_KCMQOXUX = require("./chunk-KCMQOXUX.js");
var import_chunk_FFLD75KX = require("./chunk-FFLD75KX.js");
var import_chunk_PZ4BRULM = require("./chunk-PZ4BRULM.js");
var import_chunk_2CL32XWS = require("./chunk-2CL32XWS.js");
var import_chunk_F7KSWWYN = require("./chunk-F7KSWWYN.js");
var import_chunk_FVJ3R4NJ = require("./chunk-FVJ3R4NJ.js");
var import_internals = require("@prisma/internals");
var import_prompts = __toESM(require("prompts"));
var _DbPush, DbPush;
var init_DbPush = (0, import_chunk_FVJ3R4NJ.__esm)({
  "src/commands/DbPush.ts"() {
    (0, import_chunk_F7KSWWYN.init_colors)();
    (0, import_chunk_BOP7PHOB.init_Migrate)();
    (0, import_chunk_PZ4BRULM.init_ensureDatabaseExists)();
    (0, import_chunk_2CL32XWS.init_errors)();
    (0, import_chunk_KCMQOXUX.init_getSchemaPathAndPrint)();
    (0, import_chunk_FFLD75KX.init_printDatasource)();
    _DbPush = class _DbPush2 {
      static new() {
        return new _DbPush2();
      }
      async parse(argv) {
        const args = (0, import_internals.arg)(
          argv,
          {
            "--help": Boolean,
            "-h": "--help",
            "--accept-data-loss": Boolean,
            "--force-reset": Boolean,
            "--skip-generate": Boolean,
            "--schema": String,
            "--telemetry-information": String
          },
          false
        );
        if ((0, import_internals.isError)(args)) {
          return this.help(args.message);
        }
        await (0, import_internals.checkUnsupportedDataProxy)("db push", args, true);
        if (args["--help"]) {
          return this.help();
        }
        (0, import_internals.loadEnvFile)({ schemaPath: args["--schema"], printMessage: true });
        const schemaPath = await (0, import_chunk_KCMQOXUX.getSchemaPathAndPrint)(args["--schema"]);
        const datasourceInfo = await (0, import_chunk_PZ4BRULM.getDatasourceInfo)({ schemaPath });
        (0, import_chunk_FFLD75KX.printDatasource)({ datasourceInfo });
        const migrate = new import_chunk_BOP7PHOB.Migrate(schemaPath);
        try {
          const wasDbCreated = await (0, import_chunk_PZ4BRULM.ensureDatabaseExists)("push", schemaPath);
          if (wasDbCreated) {
            console.info();
            console.info(wasDbCreated);
          }
        } catch (e) {
          console.info();
          throw e;
        }
        let wasDatabaseReset = false;
        if (args["--force-reset"]) {
          console.info();
          try {
            await migrate.reset();
          } catch (e) {
            migrate.stop();
            throw e;
          }
          let successfulResetMsg = `The ${datasourceInfo.prettyProvider} database`;
          if (datasourceInfo.dbName) {
            successfulResetMsg += ` "${datasourceInfo.dbName}"`;
          }
          const schemasLength = datasourceInfo.schemas?.length || 0;
          if (datasourceInfo.schemas && schemasLength > 0) {
            successfulResetMsg += ` schema${schemasLength > 1 ? "s" : ""} "${datasourceInfo.schemas.join(", ")}"`;
          } else if (datasourceInfo.schema) {
            successfulResetMsg += ` schema "${datasourceInfo.schema}"`;
          }
          if (datasourceInfo.dbLocation) {
            successfulResetMsg += ` at "${datasourceInfo.dbLocation}"`;
          }
          successfulResetMsg += ` ${schemasLength > 1 ? "were" : "was"} successfully reset.`;
          console.info(successfulResetMsg);
          wasDatabaseReset = true;
        }
        const before = Math.round(performance.now());
        let migration;
        try {
          migration = await migrate.push({
            force: args["--accept-data-loss"]
          });
        } catch (e) {
          migrate.stop();
          throw e;
        }
        if (migration.unexecutable && migration.unexecutable.length > 0) {
          const messages = [];
          messages.push(`${(0, import_chunk_F7KSWWYN.bold)((0, import_chunk_F7KSWWYN.red)("\n\u26A0\uFE0F We found changes that cannot be executed:\n"))}`);
          for (const item of migration.unexecutable) {
            messages.push(`  \u2022 ${item}`);
          }
          console.info();
          if (!(0, import_internals.canPrompt)()) {
            migrate.stop();
            throw new Error(`${messages.join("\n")}

Use the --force-reset flag to drop the database before push like ${(0, import_chunk_F7KSWWYN.bold)(
              (0, import_chunk_F7KSWWYN.green)((0, import_internals.getCommandWithExecutor)("prisma db push --force-reset"))
            )}
${(0, import_chunk_F7KSWWYN.bold)((0, import_chunk_F7KSWWYN.red)("All data will be lost."))}
        `);
          } else {
            console.info(`${messages.join("\n")}
`);
          }
          console.info();
          const confirmation = await (0, import_prompts.default)({
            type: "confirm",
            name: "value",
            message: `To apply this change we need to reset the database, do you want to continue? ${(0, import_chunk_F7KSWWYN.red)(
              "All data will be lost"
            )}.`
          });
          if (!confirmation.value) {
            console.info("Reset cancelled.");
            migrate.stop();
            process.exit(130);
          }
          try {
            await migrate.reset();
            if (datasourceInfo.dbName && datasourceInfo.dbLocation) {
              console.info(
                `The ${datasourceInfo.prettyProvider} database "${datasourceInfo.dbName}" from "${datasourceInfo.dbLocation}" was successfully reset.`
              );
            } else {
              console.info(`The ${datasourceInfo.prettyProvider} database was successfully reset.`);
            }
            wasDatabaseReset = true;
            await migrate.push({});
          } catch (e) {
            migrate.stop();
            throw e;
          }
        }
        if (migration.warnings && migration.warnings.length > 0) {
          console.info((0, import_chunk_F7KSWWYN.bold)((0, import_chunk_F7KSWWYN.yellow)(`
\u26A0\uFE0F  There might be data loss when applying the changes:
`)));
          for (const warning of migration.warnings) {
            console.info(`  \u2022 ${warning}`);
          }
          console.info();
          if (!args["--accept-data-loss"]) {
            if (!(0, import_internals.canPrompt)()) {
              migrate.stop();
              throw new import_chunk_2CL32XWS.DbPushIgnoreWarningsWithFlagError();
            }
            console.info();
            const confirmation = await (0, import_prompts.default)({
              type: "confirm",
              name: "value",
              message: `Do you want to ignore the warning(s)?`
            });
            if (!confirmation.value) {
              console.info("Push cancelled.");
              migrate.stop();
              process.exit(130);
            }
            try {
              await migrate.push({
                force: true
              });
            } catch (e) {
              migrate.stop();
              throw e;
            }
          }
        }
        migrate.stop();
        if (!wasDatabaseReset && migration.warnings.length === 0 && migration.executedSteps === 0) {
          console.info(`
The database is already in sync with the Prisma schema.`);
        } else {
          const migrationTimeMessage = `Done in ${(0, import_internals.formatms)(Math.round(performance.now()) - before)}`;
          const rocketEmoji = process.platform === "win32" ? "" : "\u{1F680}  ";
          const migrationSuccessStdMessage = "Your database is now in sync with your Prisma schema.";
          const migrationSuccessMongoMessage = "Your database indexes are now in sync with your Prisma schema.";
          const provider = (0, import_internals.protocolToConnectorType)(`${datasourceInfo.url?.split(":")[0]}:`);
          console.info(
            `
${rocketEmoji}${provider === "mongodb" ? migrationSuccessMongoMessage : migrationSuccessStdMessage} ${migrationTimeMessage}`
          );
        }
        if (!process.env.PRISMA_MIGRATE_SKIP_GENERATE && !args["--skip-generate"]) {
          await migrate.tryToRunGenerate();
        }
        return ``;
      }
      help(error) {
        if (error) {
          return new import_internals.HelpError(`
${(0, import_chunk_F7KSWWYN.bold)((0, import_chunk_F7KSWWYN.red)(`!`))} ${error}
${_DbPush2.help}`);
        }
        return _DbPush2.help;
      }
    };
    _DbPush.help = (0, import_internals.format)(`
${process.platform === "win32" ? "" : "\u{1F64C}  "}Push the state from your Prisma schema to your database

${(0, import_chunk_F7KSWWYN.bold)("Usage")}

  ${(0, import_chunk_F7KSWWYN.dim)("$")} prisma db push [options]

${(0, import_chunk_F7KSWWYN.bold)("Options")}

           -h, --help   Display this help message
             --schema   Custom path to your Prisma schema
   --accept-data-loss   Ignore data loss warnings
        --force-reset   Force a reset of the database before push 
      --skip-generate   Skip triggering generators (e.g. Prisma Client)

${(0, import_chunk_F7KSWWYN.bold)("Examples")}

  Push the Prisma schema state to the database
  ${(0, import_chunk_F7KSWWYN.dim)("$")} prisma db push

  Specify a schema
  ${(0, import_chunk_F7KSWWYN.dim)("$")} prisma db push --schema=./schema.prisma

  Ignore data loss warnings
  ${(0, import_chunk_F7KSWWYN.dim)("$")} prisma db push --accept-data-loss
`);
    DbPush = _DbPush;
  }
});
