"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_MQJXL3Y6_exports = {};
__export(chunk_MQJXL3Y6_exports, {
  DbPull: () => DbPull,
  init_DbPull: () => init_DbPull
});
module.exports = __toCommonJS(chunk_MQJXL3Y6_exports);
var import_chunk_C7JRFZWR = require("./chunk-C7JRFZWR.js");
var import_chunk_GJFFELEI = require("./chunk-GJFFELEI.js");
var import_chunk_IB56RZLF = require("./chunk-IB56RZLF.js");
var import_chunk_NXI7U4IE = require("./chunk-NXI7U4IE.js");
var import_chunk_7IY2ESUS = require("./chunk-7IY2ESUS.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_debug = __toESM(require("@prisma/debug"));
var import_internals = require("@prisma/internals");
var import_fs = __toESM(require("fs"));
var import_path = __toESM(require("path"));
var debug, _DbPull, DbPull;
var init_DbPull = (0, import_chunk_FVJ3R4NJ.__esm)({
  "src/commands/DbPull.ts"() {
    (0, import_chunk_F7KSWWYN.init_colors)();
    (0, import_chunk_7IY2ESUS.init_dist)();
    (0, import_chunk_NXI7U4IE.init_SchemaEngine)();
    (0, import_chunk_PZ4BRULM.init_ensureDatabaseExists)();
    (0, import_chunk_2CL32XWS.init_errors)();
    (0, import_chunk_FFLD75KX.init_printDatasource)();
    (0, import_chunk_IB56RZLF.init_printDatasources)();
    (0, import_chunk_GJFFELEI.init_removeDatasource)();
    (0, import_chunk_C7JRFZWR.init_spinner)();
    debug = (0, import_debug.default)("prisma:db:pull");
    _DbPull = class _DbPull2 {
      static new() {
        return new _DbPull2();
      }
      urlToDatasource(url, defaultProvider) {
        const provider = defaultProvider || (0, import_internals.protocolToConnectorType)(`${url.split(":")[0]}:`);
        return (0, import_chunk_IB56RZLF.printDatasources)([
          {
            config: {},
            provider,
            name: "db",
            url
          }
        ]);
      }
      async parse(argv) {
        const args = (0, import_internals.arg)(argv, {
          "--help": Boolean,
          "-h": "--help",
          "--url": String,
          "--print": Boolean,
          "--schema": String,
          "--schemas": String,
          "--force": Boolean,
          "--composite-type-depth": Number
          // optional, only on mongodb
        });
        const spinnerFactory = (0, import_chunk_C7JRFZWR.createSpinner)(!args["--print"]);
        if (args instanceof Error) {
          return this.help(args.message);
        }
        await (0, import_internals.checkUnsupportedDataProxy)("db pull", args, !args["--url"]);
        if (args["--help"]) {
          return this.help();
        }
        const url = args["--url"];
        let schemaPath = await (0, import_internals.getSchemaPath)(args["--schema"]);
        if (schemaPath && !args["--print"]) {
          console.info((0, import_chunk_F7KSWWYN.dim)(`Prisma schema loaded from ${import_path.default.relative(process.cwd(), schemaPath)}`));
          (0, import_internals.loadEnvFile)({ schemaPath: args["--schema"], printMessage: true });
          (0, import_chunk_FFLD75KX.printDatasource)({ datasourceInfo: await (0, import_chunk_PZ4BRULM.getDatasourceInfo)({ schemaPath }) });
        } else {
          (0, import_internals.loadEnvFile)({ schemaPath: args["--schema"], printMessage: false });
        }
        if (!url && !schemaPath) {
          throw new import_chunk_2CL32XWS.NoSchemaFoundError();
        }
        const { firstDatasource, schema } = await (0, import_chunk_7IY2ESUS.N)({ url, schemaPath }).when(
          (input) => input.schemaPath !== null,
          async (input) => {
            const rawSchema = import_fs.default.readFileSync(input.schemaPath, "utf-8");
            const config = await (0, import_internals.getConfig)({
              datamodel: rawSchema,
              ignoreEnvVarErrors: true
            });
            const firstDatasource2 = config.datasources[0] ? config.datasources[0] : void 0;
            if (input.url) {
              let providerFromSchema = firstDatasource2?.provider;
              if (providerFromSchema === "postgres") {
                providerFromSchema = "postgresql";
              }
              const providerFromUrl = (0, import_internals.protocolToConnectorType)(`${input.url.split(":")[0]}:`);
              const schema2 = `${this.urlToDatasource(input.url, providerFromSchema)}

${(0, import_chunk_GJFFELEI.removeDatasource)(rawSchema)}`;
              if (providerFromSchema && providerFromUrl && providerFromSchema !== providerFromUrl && Boolean(providerFromSchema === "cockroachdb" && providerFromUrl === "postgresql") === false) {
                throw new Error(
                  `The database provider found in --url (${providerFromUrl}) is different from the provider found in the Prisma schema (${providerFromSchema}).`
                );
              }
              return { firstDatasource: firstDatasource2, schema: schema2 };
            } else {
              await (0, import_internals.getConfig)({
                datamodel: rawSchema,
                ignoreEnvVarErrors: false
              });
            }
            return { firstDatasource: firstDatasource2, schema: rawSchema };
          }
        ).when(
          (input) => input.url !== void 0,
          async (input) => {
            (0, import_internals.protocolToConnectorType)(`${input.url.split(":")[0]}:`);
            const schema2 = this.urlToDatasource(input.url);
            const config = await (0, import_internals.getConfig)({
              datamodel: schema2,
              ignoreEnvVarErrors: true
            });
            return { firstDatasource: config.datasources[0], schema: schema2 };
          }
        ).run();
        if (schemaPath) {
          const schema2 = await (0, import_internals.getSchema)(args["--schema"]);
          const modelRegex = /\s*model\s*(\w+)\s*{/;
          const modelMatch = modelRegex.exec(schema2);
          const isReintrospection = modelMatch;
          if (isReintrospection && !args["--force"] && firstDatasource?.provider === "mongodb") {
            throw new Error(`Iterating on one schema using re-introspection with db pull is currently not supported with MongoDB provider.
You can explicitly ignore and override your current local schema file with ${(0, import_chunk_F7KSWWYN.green)(
              (0, import_internals.getCommandWithExecutor)("prisma db pull --force")
            )}
Some information will be lost (relations, comments, mapped fields, @ignore...), follow ${(0, import_internals.link)(
              "https://github.com/prisma/prisma/issues/9585"
            )} for more info.`);
          }
        }
        const engine = new import_chunk_NXI7U4IE.SchemaEngine({
          projectDir: schemaPath ? import_path.default.dirname(schemaPath) : process.cwd(),
          schemaPath: schemaPath ?? void 0
        });
        const basedOn = !args["--url"] && schemaPath ? ` based on datasource defined in ${(0, import_chunk_F7KSWWYN.underline)(import_path.default.relative(process.cwd(), schemaPath))}` : "";
        const introspectionSpinner = spinnerFactory(`Introspecting${basedOn}`);
        const before = Math.round(performance.now());
        let introspectionSchema = "";
        let introspectionWarnings;
        try {
          const introspectionResult = await engine.introspect({
            schema,
            force: args["--force"],
            compositeTypeDepth: args["--composite-type-depth"],
            schemas: args["--schemas"]?.split(",")
          });
          introspectionSchema = introspectionResult.datamodel;
          introspectionWarnings = introspectionResult.warnings;
          debug(`Introspection warnings`, introspectionWarnings);
        } catch (e) {
          introspectionSpinner.failure();
          if (e.code === "P4001" && introspectionSchema.trim() === "") {
            throw new Error(`
${(0, import_chunk_F7KSWWYN.red)((0, import_chunk_F7KSWWYN.bold)(`${e.code} `))}${(0, import_chunk_F7KSWWYN.red)("The introspected database was empty:")}

${(0, import_chunk_F7KSWWYN.bold)("prisma db pull")} could not create any models in your ${(0, import_chunk_F7KSWWYN.bold)(
              "schema.prisma"
            )} file and you will not be able to generate Prisma Client with the ${(0, import_chunk_F7KSWWYN.bold)(
              (0, import_internals.getCommandWithExecutor)("prisma generate")
            )} command.

${(0, import_chunk_F7KSWWYN.bold)("To fix this, you have two options:")}

- manually create a table in your database.
- make sure the database connection URL inside the ${(0, import_chunk_F7KSWWYN.bold)("datasource")} block in ${(0, import_chunk_F7KSWWYN.bold)(
              "schema.prisma"
            )} points to a database that is not empty (it must contain at least one table).

Then you can run ${(0, import_chunk_F7KSWWYN.green)((0, import_internals.getCommandWithExecutor)("prisma db pull"))} again. 
`);
          } else if (e.code === "P1003") {
            throw new Error(`
${(0, import_chunk_F7KSWWYN.red)((0, import_chunk_F7KSWWYN.bold)(`${e.code} `))}${(0, import_chunk_F7KSWWYN.red)("The introspected database does not exist:")}

${(0, import_chunk_F7KSWWYN.bold)("prisma db pull")} could not create any models in your ${(0, import_chunk_F7KSWWYN.bold)(
              "schema.prisma"
            )} file and you will not be able to generate Prisma Client with the ${(0, import_chunk_F7KSWWYN.bold)(
              (0, import_internals.getCommandWithExecutor)("prisma generate")
            )} command.

${(0, import_chunk_F7KSWWYN.bold)("To fix this, you have two options:")}

- manually create a database.
- make sure the database connection URL inside the ${(0, import_chunk_F7KSWWYN.bold)("datasource")} block in ${(0, import_chunk_F7KSWWYN.bold)(
              "schema.prisma"
            )} points to an existing database.

Then you can run ${(0, import_chunk_F7KSWWYN.green)((0, import_internals.getCommandWithExecutor)("prisma db pull"))} again. 
`);
          } else if (e.code === "P1012") {
            console.info();
            throw new Error(`${(0, import_chunk_F7KSWWYN.red)(`${e.message}`)}
Introspection failed as your current Prisma schema file is invalid

Please fix your current schema manually (using either ${(0, import_chunk_F7KSWWYN.green)(
              (0, import_internals.getCommandWithExecutor)("prisma validate")
            )} or the Prisma VS Code extension to understand what's broken and confirm you fixed it), and then run this command again.
Or run this command with the ${(0, import_chunk_F7KSWWYN.green)(
              "--force"
            )} flag to ignore your current schema and overwrite it. All local modifications will be lost.
`);
          }
          console.info();
          throw e;
        }
        const introspectionWarningsMessage = this.getWarningMessage(introspectionWarnings);
        if (args["--print"]) {
          console.log(introspectionSchema);
          if (introspectionWarningsMessage.trim().length > 0) {
            console.error(introspectionWarningsMessage.replace(/(\n)/gm, "\n// "));
          }
        } else {
          schemaPath = schemaPath || "schema.prisma";
          import_fs.default.writeFileSync(schemaPath, introspectionSchema);
          const modelsCount = (introspectionSchema.match(/^model\s+/gm) || []).length;
          const modelsCountMessage = `${modelsCount} ${modelsCount > 1 ? "models" : "model"}`;
          const typesCount = (introspectionSchema.match(/^type\s+/gm) || []).length;
          const typesCountMessage = `${typesCount} ${typesCount > 1 ? "embedded documents" : "embedded document"}`;
          let modelsAndTypesMessage;
          if (typesCount > 0) {
            modelsAndTypesMessage = `${modelsCountMessage} and ${typesCountMessage}`;
          } else {
            modelsAndTypesMessage = `${modelsCountMessage}`;
          }
          const modelsAndTypesCountMessage = modelsCount + typesCount > 1 ? `${modelsAndTypesMessage} and wrote them` : `${modelsAndTypesMessage} and wrote it`;
          introspectionSpinner.success(`Introspected ${modelsAndTypesCountMessage} into ${(0, import_chunk_F7KSWWYN.underline)(
            import_path.default.relative(process.cwd(), schemaPath)
          )} in ${(0, import_chunk_F7KSWWYN.bold)((0, import_internals.formatms)(Math.round(performance.now()) - before))}
      ${(0, import_chunk_F7KSWWYN.yellow)(introspectionWarningsMessage)}
${`Run ${(0, import_chunk_F7KSWWYN.green)((0, import_internals.getCommandWithExecutor)("prisma generate"))} to generate Prisma Client.`}`);
        }
        return "";
      }
      getWarningMessage(warnings) {
        if (warnings) {
          return `
${warnings}`;
        }
        return "";
      }
      help(error) {
        if (error) {
          return new import_internals.HelpError(`
${(0, import_chunk_F7KSWWYN.bold)((0, import_chunk_F7KSWWYN.red)(`!`))} ${error}
${_DbPull2.help}`);
        }
        return _DbPull2.help;
      }
    };
    _DbPull.help = (0, import_internals.format)(`
Pull the state from the database to the Prisma schema using introspection

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

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

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

              -h, --help   Display this help message
                 --force   Ignore current Prisma schema file
                 --print   Print the introspected Prisma schema to stdout

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

                --schema   Custom path to your Prisma schema
  --composite-type-depth   Specify the depth for introspecting composite types (e.g. Embedded Documents in MongoDB)
                           Number, default is -1 for infinite depth, 0 = off
               --schemas   Specify the database schemas to introspect. This overrides the schemas defined in the datasource block of your Prisma schema.

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

With an existing Prisma schema
  ${(0, import_chunk_F7KSWWYN.dim)("$")} prisma db pull

Or specify a Prisma schema path
  ${(0, import_chunk_F7KSWWYN.dim)("$")} prisma db pull --schema=./schema.prisma

Instead of saving the result to the filesystem, you can also print it to stdout
  ${(0, import_chunk_F7KSWWYN.dim)("$")} prisma db pull --print

Overwrite the current schema with the introspected schema instead of enriching it
  ${(0, import_chunk_F7KSWWYN.dim)("$")} prisma db pull --force

Set composite types introspection depth to 2 levels
  ${(0, import_chunk_F7KSWWYN.dim)("$")} prisma db pull --composite-type-depth=2

`);
    DbPull = _DbPull;
  }
});
