"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_EDVAGX3K_exports = {};
__export(chunk_EDVAGX3K_exports, {
  DbExecute: () => DbExecute,
  init_DbExecute: () => init_DbExecute
});
module.exports = __toCommonJS(chunk_EDVAGX3K_exports);
var import_chunk_BOP7PHOB = require("./chunk-BOP7PHOB.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_fs = __toESM(require("fs"));
var import_path = __toESM(require("path"));
var require_get_stdin = (0, import_chunk_FVJ3R4NJ.__commonJS)({
  "../../node_modules/.pnpm/get-stdin@8.0.0/node_modules/get-stdin/index.js"(exports, module2) {
    "use strict";
    var { stdin } = process;
    module2.exports = async () => {
      let result = "";
      if (stdin.isTTY) {
        return result;
      }
      stdin.setEncoding("utf8");
      for await (const chunk of stdin) {
        result += chunk;
      }
      return result;
    };
    module2.exports.buffer = async () => {
      const result = [];
      let length = 0;
      if (stdin.isTTY) {
        return Buffer.concat([]);
      }
      for await (const chunk of stdin) {
        result.push(chunk);
        length += chunk.length;
      }
      return Buffer.concat(result, length);
    };
  }
});
var import_get_stdin, helpOptions, _DbExecute, DbExecute;
var init_DbExecute = (0, import_chunk_FVJ3R4NJ.__esm)({
  "src/commands/DbExecute.ts"() {
    import_get_stdin = (0, import_chunk_FVJ3R4NJ.__toESM)(require_get_stdin());
    (0, import_chunk_F7KSWWYN.init_colors)();
    (0, import_chunk_BOP7PHOB.init_Migrate)();
    helpOptions = (0, import_internals.format)(
      `${(0, import_chunk_F7KSWWYN.bold)("Usage")}

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

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

-h, --help            Display this help message

${(0, import_chunk_F7KSWWYN.italic)("Datasource input, only 1 must be provided:")}
--url                 URL of the datasource to run the command on
--schema              Path to your Prisma schema file to take the datasource URL from

${(0, import_chunk_F7KSWWYN.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_F7KSWWYN.bold)("Flags")}

--stdin              Use the terminal standard input as the script to be executed`
    );
    _DbExecute = class _DbExecute2 {
      static new() {
        return new _DbExecute2();
      }
      async parse(argv) {
        const args = (0, import_internals.arg)(
          argv,
          {
            "--help": Boolean,
            "-h": "--help",
            "--stdin": Boolean,
            "--file": String,
            "--schema": String,
            "--url": String,
            "--telemetry-information": String
          },
          false
        );
        if ((0, import_internals.isError)(args)) {
          return this.help(args.message);
        }
        await (0, import_internals.checkUnsupportedDataProxy)("db execute", args, !args["--url"]);
        if (args["--help"]) {
          return this.help();
        }
        (0, import_internals.loadEnvFile)({ schemaPath: args["--schema"], printMessage: false });
        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_F7KSWWYN.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_F7KSWWYN.green)((0, import_internals.getCommandWithExecutor)("prisma db execute -h"))}\``
          );
        }
        if (args["--url"] && args["--schema"]) {
          throw new Error(
            `--url and --schema cannot be used at the same time. Only 1 must be provided.
See \`${(0, import_chunk_F7KSWWYN.green)((0, import_internals.getCommandWithExecutor)("prisma db execute -h"))}\``
          );
        } else if (!args["--url"] && !args["--schema"]) {
          throw new Error(
            `Either --url or --schema must be provided.
See \`${(0, import_chunk_F7KSWWYN.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 (0, import_get_stdin.default)();
        }
        let datasourceType;
        if (args["--url"]) {
          datasourceType = {
            tag: "url",
            url: args["--url"]
          };
        } else {
          const schemaPath = await (0, import_internals.getSchemaPath)(args["--schema"]);
          datasourceType = {
            tag: "schema",
            // if schemaPath is undefined, getSchemaPath will error
            schema: schemaPath
          };
        }
        const migrate = new import_chunk_BOP7PHOB.Migrate();
        try {
          await migrate.engine.dbExecute({
            script,
            datasourceType
          });
        } finally {
          migrate.stop();
        }
        return `Script executed successfully.`;
      }
      help(error) {
        if (error) {
          throw new import_internals.HelpError(`
${error}

${helpOptions}`);
        }
        return _DbExecute2.help;
      }
    };
    _DbExecute.help = (0, import_internals.format)(`
${process.platform === "win32" ? "" : "\u{1F4DD} "}Execute native commands to your database

This command takes as input a datasource, using ${(0, import_chunk_F7KSWWYN.green)(`--url`)} or ${(0, import_chunk_F7KSWWYN.green)(`--schema`)} and a script, using ${(0, import_chunk_F7KSWWYN.green)(
      `--stdin`
    )} or ${(0, import_chunk_F7KSWWYN.green)(`--file`)}.
The input parameters are mutually exclusive, only 1 of each (datasource & script) 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_F7KSWWYN.italic)(`This command is currently not supported on MongoDB.`)}

${helpOptions}
${(0, import_chunk_F7KSWWYN.bold)("Examples")}
 
  Execute the content of a SQL script file to the datasource URL taken from the schema
  ${(0, import_chunk_F7KSWWYN.dim)("$")} prisma db execute
    --file ./script.sql \\
    --schema schema.prisma

  Execute the SQL script from stdin to the datasource URL specified via the \`DATABASE_URL\` environment variable
  ${(0, import_chunk_F7KSWWYN.dim)("$")} echo 'TRUNCATE TABLE dev;' | \\
    prisma db execute \\
    --stdin \\
    --url="$DATABASE_URL"

  Like previous example, but exposing the datasource url credentials to your terminal history
  ${(0, import_chunk_F7KSWWYN.dim)("$")} echo 'TRUNCATE TABLE dev;' | \\
    prisma db execute \\
    --stdin \\
    --url="mysql://root:root@localhost/mydb"
`);
    DbExecute = _DbExecute;
  }
});
