"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_2UHNNEP4_exports = {};
__export(chunk_2UHNNEP4_exports, {
  DbPull: () => DbPull
});
module.exports = __toCommonJS(chunk_2UHNNEP4_exports);
var import_chunk_ZOT2HSX5 = require("./chunk-ZOT2HSX5.js");
var import_chunk_JZ75RIMZ = require("./chunk-JZ75RIMZ.js");
var import_chunk_RTGQXNX6 = require("./chunk-RTGQXNX6.js");
var import_chunk_JFKDSUIE = require("./chunk-JFKDSUIE.js");
var import_chunk_AHJ2N6BJ = require("./chunk-AHJ2N6BJ.js");
var import_chunk_LGYRZ6CV = require("./chunk-LGYRZ6CV.js");
var import_chunk_ZUHJASAP = require("./chunk-ZUHJASAP.js");
var import_chunk_QOPTDDIH = require("./chunk-QOPTDDIH.js");
var import_chunk_BRPS327A = require("./chunk-BRPS327A.js");
var import_chunk_RGXJYLMD = require("./chunk-RGXJYLMD.js");
var import_chunk_SKRR5WT4 = require("./chunk-SKRR5WT4.js");
var import_debug = __toESM(require("@prisma/debug"));
var import_internals = require("@prisma/internals");
var import_path = __toESM(require("path"));
var debug = (0, import_debug.default)("prisma:db:pull");
var DbPull = class _DbPull {
  static new() {
    return new _DbPull();
  }
  static help = (0, import_internals.format)(`
Pull the state from the database to the Prisma schema using introspection

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

  ${(0, import_chunk_SKRR5WT4.dim)("$")} prisma db pull [flags/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)("Flags")}

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

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

                --config   Custom path to your Prisma config file
                --schema   Custom path to your Prisma schema
                 --url     Override the datasource URL from the Prisma config file
  --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.
              --local-d1   Generate a Prisma schema from a local Cloudflare D1 database
${(0, import_chunk_SKRR5WT4.bold)("Examples")}

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

Or specify a Prisma schema path
  ${(0, import_chunk_SKRR5WT4.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_SKRR5WT4.dim)("$")} prisma db pull --print

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

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

`);
  async parse(argv, config, baseDir = process.cwd()) {
    const args = (0, import_internals.arg)(argv, {
      "--help": Boolean,
      "-h": "--help",
      "--print": Boolean,
      "--schema": String,
      "--config": String,
      "--schemas": String,
      "--force": Boolean,
      "--composite-type-depth": Number,
      // optional, only on mongodb
      "--url": String
    });
    const spinnerFactory = (0, import_chunk_ZOT2HSX5.createSpinner)(!args["--print"]);
    if (args instanceof Error) {
      return this.help(args.message);
    }
    if (args["--help"]) {
      return this.help();
    }
    const schemaContext = await (0, import_internals.loadSchemaContext)({
      schemaPath: (0, import_internals.createSchemaPathInput)({
        schemaPathFromArgs: args["--schema"],
        schemaPathFromConfig: config.schema,
        baseDir
      }),
      printLoadMessage: false,
      allowNull: true
    });
    let cmdSpecificConfig = config;
    if (args["--url"]) {
      cmdSpecificConfig = {
        ...cmdSpecificConfig,
        datasource: {
          ...cmdSpecificConfig.datasource,
          url: args["--url"]
        }
      };
    }
    const cmd = "db pull";
    const validatedConfig = (0, import_internals.validatePrismaConfigWithDatasource)({ config: cmdSpecificConfig, cmd });
    (0, import_internals.checkUnsupportedDataProxy)({ cmd, validatedConfig });
    if (schemaContext && !args["--print"]) {
      (0, import_internals.printSchemaLoadedMessage)(schemaContext.loadedFromPathForLogMessages);
      (0, import_chunk_QOPTDDIH.printDatasource)({ datasourceInfo: (0, import_chunk_BRPS327A.parseDatasourceInfo)(schemaContext?.primaryDatasource, validatedConfig) });
    }
    if (!schemaContext) {
      throw new import_chunk_ZUHJASAP.NoSchemaFoundError();
    }
    const firstDatasource = schemaContext.primaryDatasource;
    const schema = schemaContext.schemaFiles;
    await (0, import_internals.getConfig)({
      datamodel: schema
    });
    const modelRegex = /\s*model\s*(\w+)\s*{/;
    const isReintrospection = schema.some(([_, schema2]) => !!modelRegex.exec(schema2));
    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_SKRR5WT4.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 migrate = await import_chunk_RGXJYLMD.Migrate.setup({
      schemaEngineConfig: cmdSpecificConfig,
      baseDir,
      schemaContext,
      extensions: cmdSpecificConfig["extensions"]
    });
    const engine = migrate.engine;
    const basedOn = firstDatasource ? ` based on datasource defined in ${(0, import_chunk_SKRR5WT4.underline)(schemaContext.loadedFromPathForLogMessages)}` : "";
    const introspectionSpinner = spinnerFactory(`Introspecting${basedOn}`);
    const before = Math.round(performance.now());
    let introspectionSchema = void 0;
    let introspectionWarnings;
    try {
      const directoryConfig = (0, import_internals.inferDirectoryConfig)(schemaContext, cmdSpecificConfig);
      const introspectionResult = await engine.introspect({
        schema: (0, import_internals.toSchemasContainer)(schema),
        baseDirectoryPath: schemaContext?.schemaRootDir ?? process.cwd(),
        viewsDirectoryPath: directoryConfig.viewsDirPath,
        force: args["--force"],
        compositeTypeDepth: args["--composite-type-depth"],
        namespaces: args["--schemas"]?.split(",")
      });
      introspectionSchema = introspectionResult.schema;
      introspectionWarnings = introspectionResult.warnings;
      debug(`Introspection warnings`, introspectionWarnings);
    } catch (e) {
      introspectionSpinner.failure();
      if (e.code === "P4001" && (0, import_chunk_JFKDSUIE.isSchemaEmpty)(introspectionSchema)) {
        throw new Error(`
${(0, import_chunk_SKRR5WT4.red)((0, import_chunk_SKRR5WT4.bold)(`${e.code} `))}${(0, import_chunk_SKRR5WT4.red)("The introspected database was empty:")}

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

${(0, import_chunk_SKRR5WT4.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_SKRR5WT4.bold)("datasource")} block in ${(0, import_chunk_SKRR5WT4.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_SKRR5WT4.green)((0, import_internals.getCommandWithExecutor)("prisma db pull"))} again.
`);
      } else if (e.code === "P1003") {
        throw new Error(`
${(0, import_chunk_SKRR5WT4.red)((0, import_chunk_SKRR5WT4.bold)(`${e.code} `))}${(0, import_chunk_SKRR5WT4.red)("The introspected database does not exist:")}

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

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

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

Then you can run ${(0, import_chunk_SKRR5WT4.green)((0, import_internals.getCommandWithExecutor)("prisma db pull"))} again.
`);
      } else if (e.code === "P1012") {
        process.stdout.write("\n");
        const message = (0, import_internals.relativizePathInPSLError)(e.message);
        throw new Error(`${(0, import_chunk_SKRR5WT4.red)(message)}
Introspection failed as your current Prisma schema file is invalid

Please fix your current schema manually (using either ${(0, import_chunk_SKRR5WT4.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_SKRR5WT4.green)(
          "--force"
        )} flag to ignore your current schema and overwrite it. All local modifications will be lost.
`);
      }
      process.stdout.write("\n");
      throw e;
    }
    const introspectionWarningsMessage = this.getWarningMessage(introspectionWarnings);
    if (args["--print"]) {
      (0, import_chunk_AHJ2N6BJ.printIntrospectedSchema)(introspectionSchema, process.stdout);
      if (introspectionWarningsMessage.trim().length > 0) {
        console.error(introspectionWarningsMessage.replace(/(\n)/gm, "\n// "));
      }
    } else {
      if (args["--force"]) {
        await (0, import_chunk_JZ75RIMZ.removeSchemaFiles)(schema);
      }
      await (0, import_chunk_RTGQXNX6.saveSchemaFiles)(introspectionSchema);
      const { modelsCount, typesCount } = (0, import_chunk_LGYRZ6CV.countModelsAndTypes)(introspectionSchema);
      const modelsCountMessage = `${modelsCount} ${modelsCount > 1 ? "models" : "model"}`;
      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`;
      const introspectedSchemaPath = schemaContext?.loadedFromPathForLogMessages || introspectionSchema.files[0].path;
      introspectionSpinner.success(`Introspected ${modelsAndTypesCountMessage} into ${(0, import_chunk_SKRR5WT4.underline)(
        import_path.default.relative(process.cwd(), introspectedSchemaPath)
      )} in ${(0, import_chunk_SKRR5WT4.bold)((0, import_internals.formatms)(Math.round(performance.now()) - before))}
      ${(0, import_chunk_SKRR5WT4.yellow)(introspectionWarningsMessage)}
${`Run ${(0, import_chunk_SKRR5WT4.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_SKRR5WT4.bold)((0, import_chunk_SKRR5WT4.red)(`!`))} ${error}
${_DbPull.help}`);
    }
    return _DbPull.help;
  }
};
