"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_QCPYZUFF_exports = {};
__export(chunk_QCPYZUFF_exports, {
  DbExecute: () => DbExecute
});
module.exports = __toCommonJS(chunk_QCPYZUFF_exports);
var import_chunk_RGXJYLMD = require("./chunk-RGXJYLMD.js");
var import_chunk_SKRR5WT4 = require("./chunk-SKRR5WT4.js");
var import_consumers = __toESM(require("node:stream/consumers"));
var import_internals = require("@prisma/internals");
var import_fs = __toESM(require("fs"));
var import_path = __toESM(require("path"));
var helpOptions = (0, import_internals.format)(
  `${(0, import_chunk_SKRR5WT4.bold)("Usage")}

  ${(0, import_chunk_SKRR5WT4.dim)("$")} prisma db execute [options]

  The datasource URL configuration is read from the Prisma config file (e.g., ${(0, import_chunk_SKRR5WT4.italic)("prisma.config.ts")}).

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

-h, --help            Display this help message
--config              Custom path to your Prisma config file

${(0, import_chunk_SKRR5WT4.italic)("Script input, only 1 must be provided:")}
--file                Path to a file. The content will be sent as the script to be executed

${(0, import_chunk_SKRR5WT4.bold)("Flags")}

--stdin              Use the terminal standard input as the script to be executed`
);
var DbExecute = class _DbExecute {
  static new() {
    return new _DbExecute();
  }
  // TODO: This command needs to get proper support for `prisma.config.ts` eventually. Not just taking the schema path
  //  from prisma.config.ts but likely to support driver adapters, too?
  //  See https://linear.app/prisma-company/issue/ORM-639/prisma-db-execute-support-prismaconfigts-and-driver-adapters
  static help = (0, import_internals.format)(`
${process.platform === "win32" ? "" : "\u{1F4DD} "}Execute native commands to your database

This command takes as input a datasource defined in ${(0, import_chunk_SKRR5WT4.italic)("prisma.config.ts")} and a script, using ${(0, import_chunk_SKRR5WT4.green)(
    `--stdin`
  )} or ${(0, import_chunk_SKRR5WT4.green)(`--file`)}.
The script input parameters are mutually exclusive, only 1 must be provided.

The output of the command is connector-specific, and is not meant for returning data, but only to report success or failure.

On SQL databases, this command takes as input a SQL script.
The whole script will be sent as a single command to the database.

${(0, import_chunk_SKRR5WT4.italic)(`This command is currently not supported on MongoDB.`)}

${helpOptions}
${(0, import_chunk_SKRR5WT4.bold)("Examples")}

  Execute the content of a SQL script file using the datasource configured in prisma.config.ts
  ${(0, import_chunk_SKRR5WT4.dim)("$")} prisma db execute --file ./script.sql

  Execute the SQL script from stdin using the configured datasource
  ${(0, import_chunk_SKRR5WT4.dim)("$")} echo 'TRUNCATE TABLE dev;' | \\
    prisma db execute \\
    --stdin
`);
  async parse(argv, config, baseDir) {
    const args = (0, import_internals.arg)(
      argv,
      {
        "--help": Boolean,
        "-h": "--help",
        "--config": String,
        "--stdin": Boolean,
        "--file": String,
        "--telemetry-information": String
      },
      false
    );
    if ((0, import_internals.isError)(args)) {
      return this.help(args.message);
    }
    if (args["--help"]) {
      return this.help();
    }
    const cmd = "db execute";
    const validatedConfig = (0, import_internals.validatePrismaConfigWithDatasource)({ config, cmd });
    if (args["--stdin"] && args["--file"]) {
      throw new Error(
        `--stdin and --file cannot be used at the same time. Only 1 must be provided.
See \`${(0, import_chunk_SKRR5WT4.green)((0, import_internals.getCommandWithExecutor)("prisma db execute -h"))}\``
      );
    } else if (!args["--stdin"] && !args["--file"]) {
      throw new Error(
        `Either --stdin or --file must be provided.
See \`${(0, import_chunk_SKRR5WT4.green)((0, import_internals.getCommandWithExecutor)("prisma db execute -h"))}\``
      );
    }
    let script = "";
    if (args["--file"]) {
      try {
        script = import_fs.default.readFileSync(import_path.default.resolve(args["--file"]), "utf-8");
      } catch (e) {
        if (e.code === "ENOENT") {
          throw new Error(`Provided --file at ${args["--file"]} doesn't exist.`);
        } else {
          console.error(`An error occurred while reading the provided --file at ${args["--file"]}`);
          throw e;
        }
      }
    }
    if (args["--stdin"]) {
      script = await import_consumers.default.text(process.stdin);
    }
    (0, import_internals.checkUnsupportedDataProxy)({ cmd, validatedConfig });
    const datasourceType = {
      tag: "url",
      url: validatedConfig.datasource.url
    };
    const migrate = await import_chunk_RGXJYLMD.Migrate.setup({
      schemaEngineConfig: config,
      extensions: config["extensions"],
      baseDir
    });
    try {
      await migrate.engine.dbExecute({
        script,
        datasourceType
      });
    } finally {
      await migrate.stop();
    }
    return `Script executed successfully.`;
  }
  help(error) {
    if (error) {
      throw new import_internals.HelpError(`
${error}

${helpOptions}`);
    }
    return _DbExecute.help;
  }
};
