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 __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require2() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name2 in all)
    __defProp(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps = (to, from, except5, desc2) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except5)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc(from, key)) || desc2.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 __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);

// ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/ansi-styles/index.js
function assembleStyles() {
  const codes = /* @__PURE__ */ new Map();
  for (const [groupName, group] of Object.entries(styles)) {
    for (const [styleName, style] of Object.entries(group)) {
      styles[styleName] = {
        open: `\x1B[${style[0]}m`,
        close: `\x1B[${style[1]}m`
      };
      group[styleName] = styles[styleName];
      codes.set(style[0], style[1]);
    }
    Object.defineProperty(styles, groupName, {
      value: group,
      enumerable: false
    });
  }
  Object.defineProperty(styles, "codes", {
    value: codes,
    enumerable: false
  });
  styles.color.close = "\x1B[39m";
  styles.bgColor.close = "\x1B[49m";
  styles.color.ansi = wrapAnsi16();
  styles.color.ansi256 = wrapAnsi256();
  styles.color.ansi16m = wrapAnsi16m();
  styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
  styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
  styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
  Object.defineProperties(styles, {
    rgbToAnsi256: {
      value(red, green, blue) {
        if (red === green && green === blue) {
          if (red < 8) {
            return 16;
          }
          if (red > 248) {
            return 231;
          }
          return Math.round((red - 8) / 247 * 24) + 232;
        }
        return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
      },
      enumerable: false
    },
    hexToRgb: {
      value(hex) {
        const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches) {
          return [0, 0, 0];
        }
        let [colorString] = matches;
        if (colorString.length === 3) {
          colorString = [...colorString].map((character) => character + character).join("");
        }
        const integer3 = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer3 >> 16 & 255,
          integer3 >> 8 & 255,
          integer3 & 255
          /* eslint-enable no-bitwise */
        ];
      },
      enumerable: false
    },
    hexToAnsi256: {
      value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
      enumerable: false
    },
    ansi256ToAnsi: {
      value(code) {
        if (code < 8) {
          return 30 + code;
        }
        if (code < 16) {
          return 90 + (code - 8);
        }
        let red;
        let green;
        let blue;
        if (code >= 232) {
          red = ((code - 232) * 10 + 8) / 255;
          green = red;
          blue = red;
        } else {
          code -= 16;
          const remainder = code % 36;
          red = Math.floor(code / 36) / 5;
          green = Math.floor(remainder / 6) / 5;
          blue = remainder % 6 / 5;
        }
        const value = Math.max(red, green, blue) * 2;
        if (value === 0) {
          return 30;
        }
        let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
        if (value === 2) {
          result += 60;
        }
        return result;
      },
      enumerable: false
    },
    rgbToAnsi: {
      value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
      enumerable: false
    },
    hexToAnsi: {
      value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
      enumerable: false
    }
  });
  return styles;
}
var ANSI_BACKGROUND_OFFSET, wrapAnsi16, wrapAnsi256, wrapAnsi16m, styles, modifierNames, foregroundColorNames, backgroundColorNames, colorNames, ansiStyles, ansi_styles_default;
var init_ansi_styles = __esm({
  "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/ansi-styles/index.js"() {
    "use strict";
    ANSI_BACKGROUND_OFFSET = 10;
    wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
    wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
    wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
    styles = {
      modifier: {
        reset: [0, 0],
        // 21 isn't widely supported and 22 does the same thing
        bold: [1, 22],
        dim: [2, 22],
        italic: [3, 23],
        underline: [4, 24],
        overline: [53, 55],
        inverse: [7, 27],
        hidden: [8, 28],
        strikethrough: [9, 29]
      },
      color: {
        black: [30, 39],
        red: [31, 39],
        green: [32, 39],
        yellow: [33, 39],
        blue: [34, 39],
        magenta: [35, 39],
        cyan: [36, 39],
        white: [37, 39],
        // Bright color
        blackBright: [90, 39],
        gray: [90, 39],
        // Alias of `blackBright`
        grey: [90, 39],
        // Alias of `blackBright`
        redBright: [91, 39],
        greenBright: [92, 39],
        yellowBright: [93, 39],
        blueBright: [94, 39],
        magentaBright: [95, 39],
        cyanBright: [96, 39],
        whiteBright: [97, 39]
      },
      bgColor: {
        bgBlack: [40, 49],
        bgRed: [41, 49],
        bgGreen: [42, 49],
        bgYellow: [43, 49],
        bgBlue: [44, 49],
        bgMagenta: [45, 49],
        bgCyan: [46, 49],
        bgWhite: [47, 49],
        // Bright color
        bgBlackBright: [100, 49],
        bgGray: [100, 49],
        // Alias of `bgBlackBright`
        bgGrey: [100, 49],
        // Alias of `bgBlackBright`
        bgRedBright: [101, 49],
        bgGreenBright: [102, 49],
        bgYellowBright: [103, 49],
        bgBlueBright: [104, 49],
        bgMagentaBright: [105, 49],
        bgCyanBright: [106, 49],
        bgWhiteBright: [107, 49]
      }
    };
    modifierNames = Object.keys(styles.modifier);
    foregroundColorNames = Object.keys(styles.color);
    backgroundColorNames = Object.keys(styles.bgColor);
    colorNames = [...foregroundColorNames, ...backgroundColorNames];
    ansiStyles = assembleStyles();
    ansi_styles_default = ansiStyles;
  }
});

// ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/supports-color/index.js
import process2 from "process";
import os from "os";
import tty from "tty";
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
  const prefix2 = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
  const position = argv.indexOf(prefix2 + flag);
  const terminatorPosition = argv.indexOf("--");
  return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
}
function envForceColor() {
  if ("FORCE_COLOR" in env) {
    if (env.FORCE_COLOR === "true") {
      return 1;
    }
    if (env.FORCE_COLOR === "false") {
      return 0;
    }
    return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
  }
}
function translateLevel(level) {
  if (level === 0) {
    return false;
  }
  return {
    level,
    hasBasic: true,
    has256: level >= 2,
    has16m: level >= 3
  };
}
function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
  const noFlagForceColor = envForceColor();
  if (noFlagForceColor !== void 0) {
    flagForceColor = noFlagForceColor;
  }
  const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
  if (forceColor === 0) {
    return 0;
  }
  if (sniffFlags) {
    if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
      return 3;
    }
    if (hasFlag("color=256")) {
      return 2;
    }
  }
  if ("TF_BUILD" in env && "AGENT_NAME" in env) {
    return 1;
  }
  if (haveStream && !streamIsTTY && forceColor === void 0) {
    return 0;
  }
  const min2 = forceColor || 0;
  if (env.TERM === "dumb") {
    return min2;
  }
  if (process2.platform === "win32") {
    const osRelease = os.release().split(".");
    if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
      return Number(osRelease[2]) >= 14931 ? 3 : 2;
    }
    return 1;
  }
  if ("CI" in env) {
    if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
      return 3;
    }
    if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
      return 1;
    }
    return min2;
  }
  if ("TEAMCITY_VERSION" in env) {
    return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
  }
  if (env.COLORTERM === "truecolor") {
    return 3;
  }
  if (env.TERM === "xterm-kitty") {
    return 3;
  }
  if ("TERM_PROGRAM" in env) {
    const version2 = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
    switch (env.TERM_PROGRAM) {
      case "iTerm.app": {
        return version2 >= 3 ? 3 : 2;
      }
      case "Apple_Terminal": {
        return 2;
      }
    }
  }
  if (/-256(color)?$/i.test(env.TERM)) {
    return 2;
  }
  if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
    return 1;
  }
  if ("COLORTERM" in env) {
    return 1;
  }
  return min2;
}
function createSupportsColor(stream, options = {}) {
  const level = _supportsColor(stream, {
    streamIsTTY: stream && stream.isTTY,
    ...options
  });
  return translateLevel(level);
}
var env, flagForceColor, supportsColor, supports_color_default;
var init_supports_color = __esm({
  "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/supports-color/index.js"() {
    "use strict";
    ({ env } = process2);
    if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
      flagForceColor = 0;
    } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
      flagForceColor = 1;
    }
    supportsColor = {
      stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
      stderr: createSupportsColor({ isTTY: tty.isatty(2) })
    };
    supports_color_default = supportsColor;
  }
});

// ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/utilities.js
function stringReplaceAll(string, substring, replacer) {
  let index6 = string.indexOf(substring);
  if (index6 === -1) {
    return string;
  }
  const substringLength = substring.length;
  let endIndex = 0;
  let returnValue = "";
  do {
    returnValue += string.slice(endIndex, index6) + substring + replacer;
    endIndex = index6 + substringLength;
    index6 = string.indexOf(substring, endIndex);
  } while (index6 !== -1);
  returnValue += string.slice(endIndex);
  return returnValue;
}
function stringEncaseCRLFWithFirstIndex(string, prefix2, postfix, index6) {
  let endIndex = 0;
  let returnValue = "";
  do {
    const gotCR = string[index6 - 1] === "\r";
    returnValue += string.slice(endIndex, gotCR ? index6 - 1 : index6) + prefix2 + (gotCR ? "\r\n" : "\n") + postfix;
    endIndex = index6 + 1;
    index6 = string.indexOf("\n", endIndex);
  } while (index6 !== -1);
  returnValue += string.slice(endIndex);
  return returnValue;
}
var init_utilities = __esm({
  "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/utilities.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/index.js
function createChalk(options) {
  return chalkFactory(options);
}
var stdoutColor, stderrColor, GENERATOR, STYLER, IS_EMPTY, levelMapping, styles2, applyOptions, chalkFactory, getModelAnsi, usedModels, proto, createStyler, createBuilder, applyStyle, chalk, chalkStderr, source_default;
var init_source = __esm({
  "../node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/index.js"() {
    "use strict";
    init_ansi_styles();
    init_supports_color();
    init_utilities();
    ({ stdout: stdoutColor, stderr: stderrColor } = supports_color_default);
    GENERATOR = Symbol("GENERATOR");
    STYLER = Symbol("STYLER");
    IS_EMPTY = Symbol("IS_EMPTY");
    levelMapping = [
      "ansi",
      "ansi",
      "ansi256",
      "ansi16m"
    ];
    styles2 = /* @__PURE__ */ Object.create(null);
    applyOptions = (object, options = {}) => {
      if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
        throw new Error("The `level` option should be an integer from 0 to 3");
      }
      const colorLevel = stdoutColor ? stdoutColor.level : 0;
      object.level = options.level === void 0 ? colorLevel : options.level;
    };
    chalkFactory = (options) => {
      const chalk2 = (...strings) => strings.join(" ");
      applyOptions(chalk2, options);
      Object.setPrototypeOf(chalk2, createChalk.prototype);
      return chalk2;
    };
    Object.setPrototypeOf(createChalk.prototype, Function.prototype);
    for (const [styleName, style] of Object.entries(ansi_styles_default)) {
      styles2[styleName] = {
        get() {
          const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
          Object.defineProperty(this, styleName, { value: builder });
          return builder;
        }
      };
    }
    styles2.visible = {
      get() {
        const builder = createBuilder(this, this[STYLER], true);
        Object.defineProperty(this, "visible", { value: builder });
        return builder;
      }
    };
    getModelAnsi = (model, level, type, ...arguments_) => {
      if (model === "rgb") {
        if (level === "ansi16m") {
          return ansi_styles_default[type].ansi16m(...arguments_);
        }
        if (level === "ansi256") {
          return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
        }
        return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
      }
      if (model === "hex") {
        return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
      }
      return ansi_styles_default[type][model](...arguments_);
    };
    usedModels = ["rgb", "hex", "ansi256"];
    for (const model of usedModels) {
      styles2[model] = {
        get() {
          const { level } = this;
          return function(...arguments_) {
            const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
            return createBuilder(this, styler, this[IS_EMPTY]);
          };
        }
      };
      const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
      styles2[bgModel] = {
        get() {
          const { level } = this;
          return function(...arguments_) {
            const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
            return createBuilder(this, styler, this[IS_EMPTY]);
          };
        }
      };
    }
    proto = Object.defineProperties(() => {
    }, {
      ...styles2,
      level: {
        enumerable: true,
        get() {
          return this[GENERATOR].level;
        },
        set(level) {
          this[GENERATOR].level = level;
        }
      }
    });
    createStyler = (open, close, parent) => {
      let openAll;
      let closeAll;
      if (parent === void 0) {
        openAll = open;
        closeAll = close;
      } else {
        openAll = parent.openAll + open;
        closeAll = close + parent.closeAll;
      }
      return {
        open,
        close,
        openAll,
        closeAll,
        parent
      };
    };
    createBuilder = (self2, _styler, _isEmpty) => {
      const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
      Object.setPrototypeOf(builder, proto);
      builder[GENERATOR] = self2;
      builder[STYLER] = _styler;
      builder[IS_EMPTY] = _isEmpty;
      return builder;
    };
    applyStyle = (self2, string) => {
      if (self2.level <= 0 || !string) {
        return self2[IS_EMPTY] ? "" : string;
      }
      let styler = self2[STYLER];
      if (styler === void 0) {
        return string;
      }
      const { openAll, closeAll } = styler;
      if (string.includes("\x1B")) {
        while (styler !== void 0) {
          string = stringReplaceAll(string, styler.close, styler.open);
          styler = styler.parent;
        }
      }
      const lfIndex = string.indexOf("\n");
      if (lfIndex !== -1) {
        string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
      }
      return openAll + string + closeAll;
    };
    Object.defineProperties(createChalk.prototype, styles2);
    chalk = createChalk();
    chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
    source_default = chalk;
  }
});

// ../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/old.js
var require_old = __commonJS({
  "../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/old.js"(exports) {
    "use strict";
    var pathModule = __require("path");
    var isWindows = process.platform === "win32";
    var fs = __require("fs");
    var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
    function rethrow() {
      var callback;
      if (DEBUG) {
        var backtrace = new Error();
        callback = debugCallback;
      } else
        callback = missingCallback;
      return callback;
      function debugCallback(err) {
        if (err) {
          backtrace.message = err.message;
          err = backtrace;
          missingCallback(err);
        }
      }
      function missingCallback(err) {
        if (err) {
          if (process.throwDeprecation)
            throw err;
          else if (!process.noDeprecation) {
            var msg = "fs: missing callback " + (err.stack || err.message);
            if (process.traceDeprecation)
              console.trace(msg);
            else
              console.error(msg);
          }
        }
      }
    }
    function maybeCallback(cb) {
      return typeof cb === "function" ? cb : rethrow();
    }
    var normalize = pathModule.normalize;
    if (isWindows) {
      nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
    } else {
      nextPartRe = /(.*?)(?:[\/]+|$)/g;
    }
    var nextPartRe;
    if (isWindows) {
      splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
    } else {
      splitRootRe = /^[\/]*/;
    }
    var splitRootRe;
    exports.realpathSync = function realpathSync(p, cache) {
      p = pathModule.resolve(p);
      if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
        return cache[p];
      }
      var original = p, seenLinks = {}, knownHard = {};
      var pos;
      var current;
      var base;
      var previous;
      start();
      function start() {
        var m = splitRootRe.exec(p);
        pos = m[0].length;
        current = m[0];
        base = m[0];
        previous = "";
        if (isWindows && !knownHard[base]) {
          fs.lstatSync(base);
          knownHard[base] = true;
        }
      }
      while (pos < p.length) {
        nextPartRe.lastIndex = pos;
        var result = nextPartRe.exec(p);
        previous = current;
        current += result[0];
        base = previous + result[1];
        pos = nextPartRe.lastIndex;
        if (knownHard[base] || cache && cache[base] === base) {
          continue;
        }
        var resolvedLink;
        if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
          resolvedLink = cache[base];
        } else {
          var stat = fs.lstatSync(base);
          if (!stat.isSymbolicLink()) {
            knownHard[base] = true;
            if (cache) cache[base] = base;
            continue;
          }
          var linkTarget = null;
          if (!isWindows) {
            var id = stat.dev.toString(32) + ":" + stat.ino.toString(32);
            if (seenLinks.hasOwnProperty(id)) {
              linkTarget = seenLinks[id];
            }
          }
          if (linkTarget === null) {
            fs.statSync(base);
            linkTarget = fs.readlinkSync(base);
          }
          resolvedLink = pathModule.resolve(previous, linkTarget);
          if (cache) cache[base] = resolvedLink;
          if (!isWindows) seenLinks[id] = linkTarget;
        }
        p = pathModule.resolve(resolvedLink, p.slice(pos));
        start();
      }
      if (cache) cache[original] = p;
      return p;
    };
    exports.realpath = function realpath(p, cache, cb) {
      if (typeof cb !== "function") {
        cb = maybeCallback(cache);
        cache = null;
      }
      p = pathModule.resolve(p);
      if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
        return process.nextTick(cb.bind(null, null, cache[p]));
      }
      var original = p, seenLinks = {}, knownHard = {};
      var pos;
      var current;
      var base;
      var previous;
      start();
      function start() {
        var m = splitRootRe.exec(p);
        pos = m[0].length;
        current = m[0];
        base = m[0];
        previous = "";
        if (isWindows && !knownHard[base]) {
          fs.lstat(base, function(err) {
            if (err) return cb(err);
            knownHard[base] = true;
            LOOP();
          });
        } else {
          process.nextTick(LOOP);
        }
      }
      function LOOP() {
        if (pos >= p.length) {
          if (cache) cache[original] = p;
          return cb(null, p);
        }
        nextPartRe.lastIndex = pos;
        var result = nextPartRe.exec(p);
        previous = current;
        current += result[0];
        base = previous + result[1];
        pos = nextPartRe.lastIndex;
        if (knownHard[base] || cache && cache[base] === base) {
          return process.nextTick(LOOP);
        }
        if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
          return gotResolvedLink(cache[base]);
        }
        return fs.lstat(base, gotStat);
      }
      function gotStat(err, stat) {
        if (err) return cb(err);
        if (!stat.isSymbolicLink()) {
          knownHard[base] = true;
          if (cache) cache[base] = base;
          return process.nextTick(LOOP);
        }
        if (!isWindows) {
          var id = stat.dev.toString(32) + ":" + stat.ino.toString(32);
          if (seenLinks.hasOwnProperty(id)) {
            return gotTarget(null, seenLinks[id], base);
          }
        }
        fs.stat(base, function(err2) {
          if (err2) return cb(err2);
          fs.readlink(base, function(err3, target) {
            if (!isWindows) seenLinks[id] = target;
            gotTarget(err3, target);
          });
        });
      }
      function gotTarget(err, target, base2) {
        if (err) return cb(err);
        var resolvedLink = pathModule.resolve(previous, target);
        if (cache) cache[base2] = resolvedLink;
        gotResolvedLink(resolvedLink);
      }
      function gotResolvedLink(resolvedLink) {
        p = pathModule.resolve(resolvedLink, p.slice(pos));
        start();
      }
    };
  }
});

// ../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/index.js
var require_fs = __commonJS({
  "../node_modules/.pnpm/fs.realpath@1.0.0/node_modules/fs.realpath/index.js"(exports, module) {
    "use strict";
    module.exports = realpath;
    realpath.realpath = realpath;
    realpath.sync = realpathSync;
    realpath.realpathSync = realpathSync;
    realpath.monkeypatch = monkeypatch;
    realpath.unmonkeypatch = unmonkeypatch;
    var fs = __require("fs");
    var origRealpath = fs.realpath;
    var origRealpathSync = fs.realpathSync;
    var version2 = process.version;
    var ok = /^v[0-5]\./.test(version2);
    var old = require_old();
    function newError(er) {
      return er && er.syscall === "realpath" && (er.code === "ELOOP" || er.code === "ENOMEM" || er.code === "ENAMETOOLONG");
    }
    function realpath(p, cache, cb) {
      if (ok) {
        return origRealpath(p, cache, cb);
      }
      if (typeof cache === "function") {
        cb = cache;
        cache = null;
      }
      origRealpath(p, cache, function(er, result) {
        if (newError(er)) {
          old.realpath(p, cache, cb);
        } else {
          cb(er, result);
        }
      });
    }
    function realpathSync(p, cache) {
      if (ok) {
        return origRealpathSync(p, cache);
      }
      try {
        return origRealpathSync(p, cache);
      } catch (er) {
        if (newError(er)) {
          return old.realpathSync(p, cache);
        } else {
          throw er;
        }
      }
    }
    function monkeypatch() {
      fs.realpath = realpath;
      fs.realpathSync = realpathSync;
    }
    function unmonkeypatch() {
      fs.realpath = origRealpath;
      fs.realpathSync = origRealpathSync;
    }
  }
});

// ../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/lib/path.js
var require_path = __commonJS({
  "../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/lib/path.js"(exports, module) {
    "use strict";
    var isWindows = typeof process === "object" && process && process.platform === "win32";
    module.exports = isWindows ? { sep: "\\" } : { sep: "/" };
  }
});

// ../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js
var require_balanced_match = __commonJS({
  "../node_modules/.pnpm/balanced-match@1.0.2/node_modules/balanced-match/index.js"(exports, module) {
    "use strict";
    module.exports = balanced;
    function balanced(a, b, str) {
      if (a instanceof RegExp) a = maybeMatch(a, str);
      if (b instanceof RegExp) b = maybeMatch(b, str);
      var r = range(a, b, str);
      return r && {
        start: r[0],
        end: r[1],
        pre: str.slice(0, r[0]),
        body: str.slice(r[0] + a.length, r[1]),
        post: str.slice(r[1] + b.length)
      };
    }
    function maybeMatch(reg, str) {
      var m = str.match(reg);
      return m ? m[0] : null;
    }
    balanced.range = range;
    function range(a, b, str) {
      var begs, beg, left, right, result;
      var ai = str.indexOf(a);
      var bi = str.indexOf(b, ai + 1);
      var i = ai;
      if (ai >= 0 && bi > 0) {
        if (a === b) {
          return [ai, bi];
        }
        begs = [];
        left = str.length;
        while (i >= 0 && !result) {
          if (i == ai) {
            begs.push(i);
            ai = str.indexOf(a, i + 1);
          } else if (begs.length == 1) {
            result = [begs.pop(), bi];
          } else {
            beg = begs.pop();
            if (beg < left) {
              left = beg;
              right = bi;
            }
            bi = str.indexOf(b, i + 1);
          }
          i = ai < bi && ai >= 0 ? ai : bi;
        }
        if (begs.length) {
          result = [left, right];
        }
      }
      return result;
    }
  }
});

// ../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
var require_brace_expansion = __commonJS({
  "../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports, module) {
    "use strict";
    var balanced = require_balanced_match();
    module.exports = expandTop;
    var escSlash = "\0SLASH" + Math.random() + "\0";
    var escOpen = "\0OPEN" + Math.random() + "\0";
    var escClose = "\0CLOSE" + Math.random() + "\0";
    var escComma = "\0COMMA" + Math.random() + "\0";
    var escPeriod = "\0PERIOD" + Math.random() + "\0";
    function numeric3(str) {
      return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
    }
    function escapeBraces(str) {
      return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
    }
    function unescapeBraces(str) {
      return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
    }
    function parseCommaParts(str) {
      if (!str)
        return [""];
      var parts = [];
      var m = balanced("{", "}", str);
      if (!m)
        return str.split(",");
      var pre = m.pre;
      var body = m.body;
      var post = m.post;
      var p = pre.split(",");
      p[p.length - 1] += "{" + body + "}";
      var postParts = parseCommaParts(post);
      if (post.length) {
        p[p.length - 1] += postParts.shift();
        p.push.apply(p, postParts);
      }
      parts.push.apply(parts, p);
      return parts;
    }
    function expandTop(str) {
      if (!str)
        return [];
      if (str.substr(0, 2) === "{}") {
        str = "\\{\\}" + str.substr(2);
      }
      return expand2(escapeBraces(str), true).map(unescapeBraces);
    }
    function embrace(str) {
      return "{" + str + "}";
    }
    function isPadded(el) {
      return /^-?0\d/.test(el);
    }
    function lte2(i, y) {
      return i <= y;
    }
    function gte2(i, y) {
      return i >= y;
    }
    function expand2(str, isTop) {
      var expansions = [];
      var m = balanced("{", "}", str);
      if (!m) return [str];
      var pre = m.pre;
      var post = m.post.length ? expand2(m.post, false) : [""];
      if (/\$$/.test(m.pre)) {
        for (var k = 0; k < post.length; k++) {
          var expansion = pre + "{" + m.body + "}" + post[k];
          expansions.push(expansion);
        }
      } else {
        var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
        var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
        var isSequence = isNumericSequence || isAlphaSequence;
        var isOptions = m.body.indexOf(",") >= 0;
        if (!isSequence && !isOptions) {
          if (m.post.match(/,.*\}/)) {
            str = m.pre + "{" + m.body + escClose + m.post;
            return expand2(str);
          }
          return [str];
        }
        var n;
        if (isSequence) {
          n = m.body.split(/\.\./);
        } else {
          n = parseCommaParts(m.body);
          if (n.length === 1) {
            n = expand2(n[0], false).map(embrace);
            if (n.length === 1) {
              return post.map(function(p) {
                return m.pre + n[0] + p;
              });
            }
          }
        }
        var N;
        if (isSequence) {
          var x = numeric3(n[0]);
          var y = numeric3(n[1]);
          var width = Math.max(n[0].length, n[1].length);
          var incr = n.length == 3 ? Math.abs(numeric3(n[2])) : 1;
          var test = lte2;
          var reverse = y < x;
          if (reverse) {
            incr *= -1;
            test = gte2;
          }
          var pad = n.some(isPadded);
          N = [];
          for (var i = x; test(i, y); i += incr) {
            var c;
            if (isAlphaSequence) {
              c = String.fromCharCode(i);
              if (c === "\\")
                c = "";
            } else {
              c = String(i);
              if (pad) {
                var need = width - c.length;
                if (need > 0) {
                  var z = new Array(need + 1).join("0");
                  if (i < 0)
                    c = "-" + z + c.slice(1);
                  else
                    c = z + c;
                }
              }
            }
            N.push(c);
          }
        } else {
          N = [];
          for (var j = 0; j < n.length; j++) {
            N.push.apply(N, expand2(n[j], false));
          }
        }
        for (var j = 0; j < N.length; j++) {
          for (var k = 0; k < post.length; k++) {
            var expansion = pre + N[j] + post[k];
            if (!isTop || isSequence || expansion)
              expansions.push(expansion);
          }
        }
      }
      return expansions;
    }
  }
});

// ../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/minimatch.js
var require_minimatch = __commonJS({
  "../node_modules/.pnpm/minimatch@5.1.6/node_modules/minimatch/minimatch.js"(exports, module) {
    "use strict";
    var minimatch2 = module.exports = (p, pattern, options = {}) => {
      assertValidPattern2(pattern);
      if (!options.nocomment && pattern.charAt(0) === "#") {
        return false;
      }
      return new Minimatch2(pattern, options).match(p);
    };
    module.exports = minimatch2;
    var path2 = require_path();
    minimatch2.sep = path2.sep;
    var GLOBSTAR2 = Symbol("globstar **");
    minimatch2.GLOBSTAR = GLOBSTAR2;
    var expand2 = require_brace_expansion();
    var plTypes2 = {
      "!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
      "?": { open: "(?:", close: ")?" },
      "+": { open: "(?:", close: ")+" },
      "*": { open: "(?:", close: ")*" },
      "@": { open: "(?:", close: ")" }
    };
    var qmark2 = "[^/]";
    var star2 = qmark2 + "*?";
    var twoStarDot2 = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
    var twoStarNoDot2 = "(?:(?!(?:\\/|^)\\.).)*?";
    var charSet2 = (s) => s.split("").reduce((set, c) => {
      set[c] = true;
      return set;
    }, {});
    var reSpecials2 = charSet2("().*{}+?[]^$\\!");
    var addPatternStartSet2 = charSet2("[.(");
    var slashSplit = /\/+/;
    minimatch2.filter = (pattern, options = {}) => (p, i, list) => minimatch2(p, pattern, options);
    var ext2 = (a, b = {}) => {
      const t = {};
      Object.keys(a).forEach((k) => t[k] = a[k]);
      Object.keys(b).forEach((k) => t[k] = b[k]);
      return t;
    };
    minimatch2.defaults = (def) => {
      if (!def || typeof def !== "object" || !Object.keys(def).length) {
        return minimatch2;
      }
      const orig = minimatch2;
      const m = (p, pattern, options) => orig(p, pattern, ext2(def, options));
      m.Minimatch = class Minimatch extends orig.Minimatch {
        constructor(pattern, options) {
          super(pattern, ext2(def, options));
        }
      };
      m.Minimatch.defaults = (options) => orig.defaults(ext2(def, options)).Minimatch;
      m.filter = (pattern, options) => orig.filter(pattern, ext2(def, options));
      m.defaults = (options) => orig.defaults(ext2(def, options));
      m.makeRe = (pattern, options) => orig.makeRe(pattern, ext2(def, options));
      m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext2(def, options));
      m.match = (list, pattern, options) => orig.match(list, pattern, ext2(def, options));
      return m;
    };
    minimatch2.braceExpand = (pattern, options) => braceExpand2(pattern, options);
    var braceExpand2 = (pattern, options = {}) => {
      assertValidPattern2(pattern);
      if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
        return [pattern];
      }
      return expand2(pattern);
    };
    var MAX_PATTERN_LENGTH2 = 1024 * 64;
    var assertValidPattern2 = (pattern) => {
      if (typeof pattern !== "string") {
        throw new TypeError("invalid pattern");
      }
      if (pattern.length > MAX_PATTERN_LENGTH2) {
        throw new TypeError("pattern is too long");
      }
    };
    var SUBPARSE = Symbol("subparse");
    minimatch2.makeRe = (pattern, options) => new Minimatch2(pattern, options || {}).makeRe();
    minimatch2.match = (list, pattern, options = {}) => {
      const mm = new Minimatch2(pattern, options);
      list = list.filter((f) => mm.match(f));
      if (mm.options.nonull && !list.length) {
        list.push(pattern);
      }
      return list;
    };
    var globUnescape2 = (s) => s.replace(/\\(.)/g, "$1");
    var charUnescape = (s) => s.replace(/\\([^-\]])/g, "$1");
    var regExpEscape2 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    var braExpEscape = (s) => s.replace(/[[\]\\]/g, "\\$&");
    var Minimatch2 = class {
      constructor(pattern, options) {
        assertValidPattern2(pattern);
        if (!options) options = {};
        this.options = options;
        this.set = [];
        this.pattern = pattern;
        this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
        if (this.windowsPathsNoEscape) {
          this.pattern = this.pattern.replace(/\\/g, "/");
        }
        this.regexp = null;
        this.negate = false;
        this.comment = false;
        this.empty = false;
        this.partial = !!options.partial;
        this.make();
      }
      debug() {
      }
      make() {
        const pattern = this.pattern;
        const options = this.options;
        if (!options.nocomment && pattern.charAt(0) === "#") {
          this.comment = true;
          return;
        }
        if (!pattern) {
          this.empty = true;
          return;
        }
        this.parseNegate();
        let set = this.globSet = this.braceExpand();
        if (options.debug) this.debug = (...args) => console.error(...args);
        this.debug(this.pattern, set);
        set = this.globParts = set.map((s) => s.split(slashSplit));
        this.debug(this.pattern, set);
        set = set.map((s, si, set2) => s.map(this.parse, this));
        this.debug(this.pattern, set);
        set = set.filter((s) => s.indexOf(false) === -1);
        this.debug(this.pattern, set);
        this.set = set;
      }
      parseNegate() {
        if (this.options.nonegate) return;
        const pattern = this.pattern;
        let negate = false;
        let negateOffset = 0;
        for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {
          negate = !negate;
          negateOffset++;
        }
        if (negateOffset) this.pattern = pattern.slice(negateOffset);
        this.negate = negate;
      }
      // set partial to true to test if, for example,
      // "/a/b" matches the start of "/*/b/*/d"
      // Partial means, if you run out of file before you run
      // out of pattern, then that's fine, as long as all
      // the parts match.
      matchOne(file, pattern, partial) {
        var options = this.options;
        this.debug(
          "matchOne",
          { "this": this, file, pattern }
        );
        this.debug("matchOne", file.length, pattern.length);
        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
          this.debug("matchOne loop");
          var p = pattern[pi];
          var f = file[fi];
          this.debug(pattern, p, f);
          if (p === false) return false;
          if (p === GLOBSTAR2) {
            this.debug("GLOBSTAR", [pattern, p, f]);
            var fr = fi;
            var pr = pi + 1;
            if (pr === pl) {
              this.debug("** at the end");
              for (; fi < fl; fi++) {
                if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false;
              }
              return true;
            }
            while (fr < fl) {
              var swallowee = file[fr];
              this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
              if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
                this.debug("globstar found match!", fr, fl, swallowee);
                return true;
              } else {
                if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
                  this.debug("dot detected!", file, fr, pattern, pr);
                  break;
                }
                this.debug("globstar swallow a segment, and continue");
                fr++;
              }
            }
            if (partial) {
              this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
              if (fr === fl) return true;
            }
            return false;
          }
          var hit;
          if (typeof p === "string") {
            hit = f === p;
            this.debug("string match", p, f, hit);
          } else {
            hit = f.match(p);
            this.debug("pattern match", p, f, hit);
          }
          if (!hit) return false;
        }
        if (fi === fl && pi === pl) {
          return true;
        } else if (fi === fl) {
          return partial;
        } else if (pi === pl) {
          return fi === fl - 1 && file[fi] === "";
        }
        throw new Error("wtf?");
      }
      braceExpand() {
        return braceExpand2(this.pattern, this.options);
      }
      parse(pattern, isSub) {
        assertValidPattern2(pattern);
        const options = this.options;
        if (pattern === "**") {
          if (!options.noglobstar)
            return GLOBSTAR2;
          else
            pattern = "*";
        }
        if (pattern === "") return "";
        let re = "";
        let hasMagic = false;
        let escaping = false;
        const patternListStack = [];
        const negativeLists = [];
        let stateChar;
        let inClass = false;
        let reClassStart = -1;
        let classStart = -1;
        let cs;
        let pl;
        let sp;
        let dotTravAllowed = pattern.charAt(0) === ".";
        let dotFileAllowed = options.dot || dotTravAllowed;
        const patternStart = () => dotTravAllowed ? "" : dotFileAllowed ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
        const subPatternStart = (p) => p.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
        const clearStateChar = () => {
          if (stateChar) {
            switch (stateChar) {
              case "*":
                re += star2;
                hasMagic = true;
                break;
              case "?":
                re += qmark2;
                hasMagic = true;
                break;
              default:
                re += "\\" + stateChar;
                break;
            }
            this.debug("clearStateChar %j %j", stateChar, re);
            stateChar = false;
          }
        };
        for (let i = 0, c; i < pattern.length && (c = pattern.charAt(i)); i++) {
          this.debug("%s	%s %s %j", pattern, i, re, c);
          if (escaping) {
            if (c === "/") {
              return false;
            }
            if (reSpecials2[c]) {
              re += "\\";
            }
            re += c;
            escaping = false;
            continue;
          }
          switch (c) {
            /* istanbul ignore next */
            case "/": {
              return false;
            }
            case "\\":
              if (inClass && pattern.charAt(i + 1) === "-") {
                re += c;
                continue;
              }
              clearStateChar();
              escaping = true;
              continue;
            // the various stateChar values
            // for the "extglob" stuff.
            case "?":
            case "*":
            case "+":
            case "@":
            case "!":
              this.debug("%s	%s %s %j <-- stateChar", pattern, i, re, c);
              if (inClass) {
                this.debug("  in class");
                if (c === "!" && i === classStart + 1) c = "^";
                re += c;
                continue;
              }
              this.debug("call clearStateChar %j", stateChar);
              clearStateChar();
              stateChar = c;
              if (options.noext) clearStateChar();
              continue;
            case "(": {
              if (inClass) {
                re += "(";
                continue;
              }
              if (!stateChar) {
                re += "\\(";
                continue;
              }
              const plEntry = {
                type: stateChar,
                start: i - 1,
                reStart: re.length,
                open: plTypes2[stateChar].open,
                close: plTypes2[stateChar].close
              };
              this.debug(this.pattern, "	", plEntry);
              patternListStack.push(plEntry);
              re += plEntry.open;
              if (plEntry.start === 0 && plEntry.type !== "!") {
                dotTravAllowed = true;
                re += subPatternStart(pattern.slice(i + 1));
              }
              this.debug("plType %j %j", stateChar, re);
              stateChar = false;
              continue;
            }
            case ")": {
              const plEntry = patternListStack[patternListStack.length - 1];
              if (inClass || !plEntry) {
                re += "\\)";
                continue;
              }
              patternListStack.pop();
              clearStateChar();
              hasMagic = true;
              pl = plEntry;
              re += pl.close;
              if (pl.type === "!") {
                negativeLists.push(Object.assign(pl, { reEnd: re.length }));
              }
              continue;
            }
            case "|": {
              const plEntry = patternListStack[patternListStack.length - 1];
              if (inClass || !plEntry) {
                re += "\\|";
                continue;
              }
              clearStateChar();
              re += "|";
              if (plEntry.start === 0 && plEntry.type !== "!") {
                dotTravAllowed = true;
                re += subPatternStart(pattern.slice(i + 1));
              }
              continue;
            }
            // these are mostly the same in regexp and glob
            case "[":
              clearStateChar();
              if (inClass) {
                re += "\\" + c;
                continue;
              }
              inClass = true;
              classStart = i;
              reClassStart = re.length;
              re += c;
              continue;
            case "]":
              if (i === classStart + 1 || !inClass) {
                re += "\\" + c;
                continue;
              }
              cs = pattern.substring(classStart + 1, i);
              try {
                RegExp("[" + braExpEscape(charUnescape(cs)) + "]");
                re += c;
              } catch (er) {
                re = re.substring(0, reClassStart) + "(?:$.)";
              }
              hasMagic = true;
              inClass = false;
              continue;
            default:
              clearStateChar();
              if (reSpecials2[c] && !(c === "^" && inClass)) {
                re += "\\";
              }
              re += c;
              break;
          }
        }
        if (inClass) {
          cs = pattern.slice(classStart + 1);
          sp = this.parse(cs, SUBPARSE);
          re = re.substring(0, reClassStart) + "\\[" + sp[0];
          hasMagic = hasMagic || sp[1];
        }
        for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
          let tail;
          tail = re.slice(pl.reStart + pl.open.length);
          this.debug("setting tail", re, pl);
          tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_2, $1, $2) => {
            if (!$2) {
              $2 = "\\";
            }
            return $1 + $1 + $2 + "|";
          });
          this.debug("tail=%j\n   %s", tail, tail, pl, re);
          const t = pl.type === "*" ? star2 : pl.type === "?" ? qmark2 : "\\" + pl.type;
          hasMagic = true;
          re = re.slice(0, pl.reStart) + t + "\\(" + tail;
        }
        clearStateChar();
        if (escaping) {
          re += "\\\\";
        }
        const addPatternStart = addPatternStartSet2[re.charAt(0)];
        for (let n = negativeLists.length - 1; n > -1; n--) {
          const nl = negativeLists[n];
          const nlBefore = re.slice(0, nl.reStart);
          const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
          let nlAfter = re.slice(nl.reEnd);
          const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
          const closeParensBefore = nlBefore.split(")").length;
          const openParensBefore = nlBefore.split("(").length - closeParensBefore;
          let cleanAfter = nlAfter;
          for (let i = 0; i < openParensBefore; i++) {
            cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
          }
          nlAfter = cleanAfter;
          const dollar = nlAfter === "" && isSub !== SUBPARSE ? "(?:$|\\/)" : "";
          re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
        }
        if (re !== "" && hasMagic) {
          re = "(?=.)" + re;
        }
        if (addPatternStart) {
          re = patternStart() + re;
        }
        if (isSub === SUBPARSE) {
          return [re, hasMagic];
        }
        if (options.nocase && !hasMagic) {
          hasMagic = pattern.toUpperCase() !== pattern.toLowerCase();
        }
        if (!hasMagic) {
          return globUnescape2(pattern);
        }
        const flags = options.nocase ? "i" : "";
        try {
          return Object.assign(new RegExp("^" + re + "$", flags), {
            _glob: pattern,
            _src: re
          });
        } catch (er) {
          return new RegExp("$.");
        }
      }
      makeRe() {
        if (this.regexp || this.regexp === false) return this.regexp;
        const set = this.set;
        if (!set.length) {
          this.regexp = false;
          return this.regexp;
        }
        const options = this.options;
        const twoStar = options.noglobstar ? star2 : options.dot ? twoStarDot2 : twoStarNoDot2;
        const flags = options.nocase ? "i" : "";
        let re = set.map((pattern) => {
          pattern = pattern.map(
            (p) => typeof p === "string" ? regExpEscape2(p) : p === GLOBSTAR2 ? GLOBSTAR2 : p._src
          ).reduce((set2, p) => {
            if (!(set2[set2.length - 1] === GLOBSTAR2 && p === GLOBSTAR2)) {
              set2.push(p);
            }
            return set2;
          }, []);
          pattern.forEach((p, i) => {
            if (p !== GLOBSTAR2 || pattern[i - 1] === GLOBSTAR2) {
              return;
            }
            if (i === 0) {
              if (pattern.length > 1) {
                pattern[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + pattern[i + 1];
              } else {
                pattern[i] = twoStar;
              }
            } else if (i === pattern.length - 1) {
              pattern[i - 1] += "(?:\\/|" + twoStar + ")?";
            } else {
              pattern[i - 1] += "(?:\\/|\\/" + twoStar + "\\/)" + pattern[i + 1];
              pattern[i + 1] = GLOBSTAR2;
            }
          });
          return pattern.filter((p) => p !== GLOBSTAR2).join("/");
        }).join("|");
        re = "^(?:" + re + ")$";
        if (this.negate) re = "^(?!" + re + ").*$";
        try {
          this.regexp = new RegExp(re, flags);
        } catch (ex) {
          this.regexp = false;
        }
        return this.regexp;
      }
      match(f, partial = this.partial) {
        this.debug("match", f, this.pattern);
        if (this.comment) return false;
        if (this.empty) return f === "";
        if (f === "/" && partial) return true;
        const options = this.options;
        if (path2.sep !== "/") {
          f = f.split(path2.sep).join("/");
        }
        f = f.split(slashSplit);
        this.debug(this.pattern, "split", f);
        const set = this.set;
        this.debug(this.pattern, "set", set);
        let filename;
        for (let i = f.length - 1; i >= 0; i--) {
          filename = f[i];
          if (filename) break;
        }
        for (let i = 0; i < set.length; i++) {
          const pattern = set[i];
          let file = f;
          if (options.matchBase && pattern.length === 1) {
            file = [filename];
          }
          const hit = this.matchOne(file, pattern, partial);
          if (hit) {
            if (options.flipNegate) return true;
            return !this.negate;
          }
        }
        if (options.flipNegate) return false;
        return this.negate;
      }
      static defaults(def) {
        return minimatch2.defaults(def).Minimatch;
      }
    };
    minimatch2.Minimatch = Minimatch2;
  }
});

// ../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js
var require_inherits_browser = __commonJS({
  "../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits_browser.js"(exports, module) {
    "use strict";
    if (typeof Object.create === "function") {
      module.exports = function inherits(ctor, superCtor) {
        if (superCtor) {
          ctor.super_ = superCtor;
          ctor.prototype = Object.create(superCtor.prototype, {
            constructor: {
              value: ctor,
              enumerable: false,
              writable: true,
              configurable: true
            }
          });
        }
      };
    } else {
      module.exports = function inherits(ctor, superCtor) {
        if (superCtor) {
          ctor.super_ = superCtor;
          var TempCtor = function() {
          };
          TempCtor.prototype = superCtor.prototype;
          ctor.prototype = new TempCtor();
          ctor.prototype.constructor = ctor;
        }
      };
    }
  }
});

// ../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js
var require_inherits = __commonJS({
  "../node_modules/.pnpm/inherits@2.0.4/node_modules/inherits/inherits.js"(exports, module) {
    "use strict";
    try {
      util2 = __require("util");
      if (typeof util2.inherits !== "function") throw "";
      module.exports = util2.inherits;
    } catch (e) {
      module.exports = require_inherits_browser();
    }
    var util2;
  }
});

// ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/common.js
var require_common = __commonJS({
  "../node_modules/.pnpm/glob@8.1.0/node_modules/glob/common.js"(exports) {
    "use strict";
    exports.setopts = setopts;
    exports.ownProp = ownProp;
    exports.makeAbs = makeAbs;
    exports.finish = finish;
    exports.mark = mark;
    exports.isIgnored = isIgnored;
    exports.childrenIgnored = childrenIgnored;
    function ownProp(obj, field) {
      return Object.prototype.hasOwnProperty.call(obj, field);
    }
    var fs = __require("fs");
    var path2 = __require("path");
    var minimatch2 = require_minimatch();
    var isAbsolute = __require("path").isAbsolute;
    var Minimatch2 = minimatch2.Minimatch;
    function alphasort(a, b) {
      return a.localeCompare(b, "en");
    }
    function setupIgnores(self2, options) {
      self2.ignore = options.ignore || [];
      if (!Array.isArray(self2.ignore))
        self2.ignore = [self2.ignore];
      if (self2.ignore.length) {
        self2.ignore = self2.ignore.map(ignoreMap);
      }
    }
    function ignoreMap(pattern) {
      var gmatcher = null;
      if (pattern.slice(-3) === "/**") {
        var gpattern = pattern.replace(/(\/\*\*)+$/, "");
        gmatcher = new Minimatch2(gpattern, { dot: true });
      }
      return {
        matcher: new Minimatch2(pattern, { dot: true }),
        gmatcher
      };
    }
    function setopts(self2, pattern, options) {
      if (!options)
        options = {};
      if (options.matchBase && -1 === pattern.indexOf("/")) {
        if (options.noglobstar) {
          throw new Error("base matching requires globstar");
        }
        pattern = "**/" + pattern;
      }
      self2.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
      if (self2.windowsPathsNoEscape) {
        pattern = pattern.replace(/\\/g, "/");
      }
      self2.silent = !!options.silent;
      self2.pattern = pattern;
      self2.strict = options.strict !== false;
      self2.realpath = !!options.realpath;
      self2.realpathCache = options.realpathCache || /* @__PURE__ */ Object.create(null);
      self2.follow = !!options.follow;
      self2.dot = !!options.dot;
      self2.mark = !!options.mark;
      self2.nodir = !!options.nodir;
      if (self2.nodir)
        self2.mark = true;
      self2.sync = !!options.sync;
      self2.nounique = !!options.nounique;
      self2.nonull = !!options.nonull;
      self2.nosort = !!options.nosort;
      self2.nocase = !!options.nocase;
      self2.stat = !!options.stat;
      self2.noprocess = !!options.noprocess;
      self2.absolute = !!options.absolute;
      self2.fs = options.fs || fs;
      self2.maxLength = options.maxLength || Infinity;
      self2.cache = options.cache || /* @__PURE__ */ Object.create(null);
      self2.statCache = options.statCache || /* @__PURE__ */ Object.create(null);
      self2.symlinks = options.symlinks || /* @__PURE__ */ Object.create(null);
      setupIgnores(self2, options);
      self2.changedCwd = false;
      var cwd = process.cwd();
      if (!ownProp(options, "cwd"))
        self2.cwd = path2.resolve(cwd);
      else {
        self2.cwd = path2.resolve(options.cwd);
        self2.changedCwd = self2.cwd !== cwd;
      }
      self2.root = options.root || path2.resolve(self2.cwd, "/");
      self2.root = path2.resolve(self2.root);
      self2.cwdAbs = isAbsolute(self2.cwd) ? self2.cwd : makeAbs(self2, self2.cwd);
      self2.nomount = !!options.nomount;
      if (process.platform === "win32") {
        self2.root = self2.root.replace(/\\/g, "/");
        self2.cwd = self2.cwd.replace(/\\/g, "/");
        self2.cwdAbs = self2.cwdAbs.replace(/\\/g, "/");
      }
      options.nonegate = true;
      options.nocomment = true;
      self2.minimatch = new Minimatch2(pattern, options);
      self2.options = self2.minimatch.options;
    }
    function finish(self2) {
      var nou = self2.nounique;
      var all = nou ? [] : /* @__PURE__ */ Object.create(null);
      for (var i = 0, l = self2.matches.length; i < l; i++) {
        var matches = self2.matches[i];
        if (!matches || Object.keys(matches).length === 0) {
          if (self2.nonull) {
            var literal = self2.minimatch.globSet[i];
            if (nou)
              all.push(literal);
            else
              all[literal] = true;
          }
        } else {
          var m = Object.keys(matches);
          if (nou)
            all.push.apply(all, m);
          else
            m.forEach(function(m2) {
              all[m2] = true;
            });
        }
      }
      if (!nou)
        all = Object.keys(all);
      if (!self2.nosort)
        all = all.sort(alphasort);
      if (self2.mark) {
        for (var i = 0; i < all.length; i++) {
          all[i] = self2._mark(all[i]);
        }
        if (self2.nodir) {
          all = all.filter(function(e) {
            var notDir = !/\/$/.test(e);
            var c = self2.cache[e] || self2.cache[makeAbs(self2, e)];
            if (notDir && c)
              notDir = c !== "DIR" && !Array.isArray(c);
            return notDir;
          });
        }
      }
      if (self2.ignore.length)
        all = all.filter(function(m2) {
          return !isIgnored(self2, m2);
        });
      self2.found = all;
    }
    function mark(self2, p) {
      var abs = makeAbs(self2, p);
      var c = self2.cache[abs];
      var m = p;
      if (c) {
        var isDir = c === "DIR" || Array.isArray(c);
        var slash = p.slice(-1) === "/";
        if (isDir && !slash)
          m += "/";
        else if (!isDir && slash)
          m = m.slice(0, -1);
        if (m !== p) {
          var mabs = makeAbs(self2, m);
          self2.statCache[mabs] = self2.statCache[abs];
          self2.cache[mabs] = self2.cache[abs];
        }
      }
      return m;
    }
    function makeAbs(self2, f) {
      var abs = f;
      if (f.charAt(0) === "/") {
        abs = path2.join(self2.root, f);
      } else if (isAbsolute(f) || f === "") {
        abs = f;
      } else if (self2.changedCwd) {
        abs = path2.resolve(self2.cwd, f);
      } else {
        abs = path2.resolve(f);
      }
      if (process.platform === "win32")
        abs = abs.replace(/\\/g, "/");
      return abs;
    }
    function isIgnored(self2, path3) {
      if (!self2.ignore.length)
        return false;
      return self2.ignore.some(function(item) {
        return item.matcher.match(path3) || !!(item.gmatcher && item.gmatcher.match(path3));
      });
    }
    function childrenIgnored(self2, path3) {
      if (!self2.ignore.length)
        return false;
      return self2.ignore.some(function(item) {
        return !!(item.gmatcher && item.gmatcher.match(path3));
      });
    }
  }
});

// ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/sync.js
var require_sync = __commonJS({
  "../node_modules/.pnpm/glob@8.1.0/node_modules/glob/sync.js"(exports, module) {
    "use strict";
    module.exports = globSync;
    globSync.GlobSync = GlobSync;
    var rp = require_fs();
    var minimatch2 = require_minimatch();
    var Minimatch2 = minimatch2.Minimatch;
    var Glob = require_glob().Glob;
    var util2 = __require("util");
    var path2 = __require("path");
    var assert = __require("assert");
    var isAbsolute = __require("path").isAbsolute;
    var common = require_common();
    var setopts = common.setopts;
    var ownProp = common.ownProp;
    var childrenIgnored = common.childrenIgnored;
    var isIgnored = common.isIgnored;
    function globSync(pattern, options) {
      if (typeof options === "function" || arguments.length === 3)
        throw new TypeError("callback provided to sync glob\nSee: https://github.com/isaacs/node-glob/issues/167");
      return new GlobSync(pattern, options).found;
    }
    function GlobSync(pattern, options) {
      if (!pattern)
        throw new Error("must provide pattern");
      if (typeof options === "function" || arguments.length === 3)
        throw new TypeError("callback provided to sync glob\nSee: https://github.com/isaacs/node-glob/issues/167");
      if (!(this instanceof GlobSync))
        return new GlobSync(pattern, options);
      setopts(this, pattern, options);
      if (this.noprocess)
        return this;
      var n = this.minimatch.set.length;
      this.matches = new Array(n);
      for (var i = 0; i < n; i++) {
        this._process(this.minimatch.set[i], i, false);
      }
      this._finish();
    }
    GlobSync.prototype._finish = function() {
      assert.ok(this instanceof GlobSync);
      if (this.realpath) {
        var self2 = this;
        this.matches.forEach(function(matchset, index6) {
          var set = self2.matches[index6] = /* @__PURE__ */ Object.create(null);
          for (var p in matchset) {
            try {
              p = self2._makeAbs(p);
              var real5 = rp.realpathSync(p, self2.realpathCache);
              set[real5] = true;
            } catch (er) {
              if (er.syscall === "stat")
                set[self2._makeAbs(p)] = true;
              else
                throw er;
            }
          }
        });
      }
      common.finish(this);
    };
    GlobSync.prototype._process = function(pattern, index6, inGlobStar) {
      assert.ok(this instanceof GlobSync);
      var n = 0;
      while (typeof pattern[n] === "string") {
        n++;
      }
      var prefix2;
      switch (n) {
        // if not, then this is rather simple
        case pattern.length:
          this._processSimple(pattern.join("/"), index6);
          return;
        case 0:
          prefix2 = null;
          break;
        default:
          prefix2 = pattern.slice(0, n).join("/");
          break;
      }
      var remain = pattern.slice(n);
      var read;
      if (prefix2 === null)
        read = ".";
      else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p) {
        return typeof p === "string" ? p : "[*]";
      }).join("/"))) {
        if (!prefix2 || !isAbsolute(prefix2))
          prefix2 = "/" + prefix2;
        read = prefix2;
      } else
        read = prefix2;
      var abs = this._makeAbs(read);
      if (childrenIgnored(this, read))
        return;
      var isGlobStar = remain[0] === minimatch2.GLOBSTAR;
      if (isGlobStar)
        this._processGlobStar(prefix2, read, abs, remain, index6, inGlobStar);
      else
        this._processReaddir(prefix2, read, abs, remain, index6, inGlobStar);
    };
    GlobSync.prototype._processReaddir = function(prefix2, read, abs, remain, index6, inGlobStar) {
      var entries = this._readdir(abs, inGlobStar);
      if (!entries)
        return;
      var pn = remain[0];
      var negate = !!this.minimatch.negate;
      var rawGlob = pn._glob;
      var dotOk = this.dot || rawGlob.charAt(0) === ".";
      var matchedEntries = [];
      for (var i = 0; i < entries.length; i++) {
        var e = entries[i];
        if (e.charAt(0) !== "." || dotOk) {
          var m;
          if (negate && !prefix2) {
            m = !e.match(pn);
          } else {
            m = e.match(pn);
          }
          if (m)
            matchedEntries.push(e);
        }
      }
      var len = matchedEntries.length;
      if (len === 0)
        return;
      if (remain.length === 1 && !this.mark && !this.stat) {
        if (!this.matches[index6])
          this.matches[index6] = /* @__PURE__ */ Object.create(null);
        for (var i = 0; i < len; i++) {
          var e = matchedEntries[i];
          if (prefix2) {
            if (prefix2.slice(-1) !== "/")
              e = prefix2 + "/" + e;
            else
              e = prefix2 + e;
          }
          if (e.charAt(0) === "/" && !this.nomount) {
            e = path2.join(this.root, e);
          }
          this._emitMatch(index6, e);
        }
        return;
      }
      remain.shift();
      for (var i = 0; i < len; i++) {
        var e = matchedEntries[i];
        var newPattern;
        if (prefix2)
          newPattern = [prefix2, e];
        else
          newPattern = [e];
        this._process(newPattern.concat(remain), index6, inGlobStar);
      }
    };
    GlobSync.prototype._emitMatch = function(index6, e) {
      if (isIgnored(this, e))
        return;
      var abs = this._makeAbs(e);
      if (this.mark)
        e = this._mark(e);
      if (this.absolute) {
        e = abs;
      }
      if (this.matches[index6][e])
        return;
      if (this.nodir) {
        var c = this.cache[abs];
        if (c === "DIR" || Array.isArray(c))
          return;
      }
      this.matches[index6][e] = true;
      if (this.stat)
        this._stat(e);
    };
    GlobSync.prototype._readdirInGlobStar = function(abs) {
      if (this.follow)
        return this._readdir(abs, false);
      var entries;
      var lstat;
      var stat;
      try {
        lstat = this.fs.lstatSync(abs);
      } catch (er) {
        if (er.code === "ENOENT") {
          return null;
        }
      }
      var isSym = lstat && lstat.isSymbolicLink();
      this.symlinks[abs] = isSym;
      if (!isSym && lstat && !lstat.isDirectory())
        this.cache[abs] = "FILE";
      else
        entries = this._readdir(abs, false);
      return entries;
    };
    GlobSync.prototype._readdir = function(abs, inGlobStar) {
      var entries;
      if (inGlobStar && !ownProp(this.symlinks, abs))
        return this._readdirInGlobStar(abs);
      if (ownProp(this.cache, abs)) {
        var c = this.cache[abs];
        if (!c || c === "FILE")
          return null;
        if (Array.isArray(c))
          return c;
      }
      try {
        return this._readdirEntries(abs, this.fs.readdirSync(abs));
      } catch (er) {
        this._readdirError(abs, er);
        return null;
      }
    };
    GlobSync.prototype._readdirEntries = function(abs, entries) {
      if (!this.mark && !this.stat) {
        for (var i = 0; i < entries.length; i++) {
          var e = entries[i];
          if (abs === "/")
            e = abs + e;
          else
            e = abs + "/" + e;
          this.cache[e] = true;
        }
      }
      this.cache[abs] = entries;
      return entries;
    };
    GlobSync.prototype._readdirError = function(f, er) {
      switch (er.code) {
        case "ENOTSUP":
        // https://github.com/isaacs/node-glob/issues/205
        case "ENOTDIR":
          var abs = this._makeAbs(f);
          this.cache[abs] = "FILE";
          if (abs === this.cwdAbs) {
            var error2 = new Error(er.code + " invalid cwd " + this.cwd);
            error2.path = this.cwd;
            error2.code = er.code;
            throw error2;
          }
          break;
        case "ENOENT":
        // not terribly unusual
        case "ELOOP":
        case "ENAMETOOLONG":
        case "UNKNOWN":
          this.cache[this._makeAbs(f)] = false;
          break;
        default:
          this.cache[this._makeAbs(f)] = false;
          if (this.strict)
            throw er;
          if (!this.silent)
            console.error("glob error", er);
          break;
      }
    };
    GlobSync.prototype._processGlobStar = function(prefix2, read, abs, remain, index6, inGlobStar) {
      var entries = this._readdir(abs, inGlobStar);
      if (!entries)
        return;
      var remainWithoutGlobStar = remain.slice(1);
      var gspref = prefix2 ? [prefix2] : [];
      var noGlobStar = gspref.concat(remainWithoutGlobStar);
      this._process(noGlobStar, index6, false);
      var len = entries.length;
      var isSym = this.symlinks[abs];
      if (isSym && inGlobStar)
        return;
      for (var i = 0; i < len; i++) {
        var e = entries[i];
        if (e.charAt(0) === "." && !this.dot)
          continue;
        var instead = gspref.concat(entries[i], remainWithoutGlobStar);
        this._process(instead, index6, true);
        var below = gspref.concat(entries[i], remain);
        this._process(below, index6, true);
      }
    };
    GlobSync.prototype._processSimple = function(prefix2, index6) {
      var exists2 = this._stat(prefix2);
      if (!this.matches[index6])
        this.matches[index6] = /* @__PURE__ */ Object.create(null);
      if (!exists2)
        return;
      if (prefix2 && isAbsolute(prefix2) && !this.nomount) {
        var trail = /[\/\\]$/.test(prefix2);
        if (prefix2.charAt(0) === "/") {
          prefix2 = path2.join(this.root, prefix2);
        } else {
          prefix2 = path2.resolve(this.root, prefix2);
          if (trail)
            prefix2 += "/";
        }
      }
      if (process.platform === "win32")
        prefix2 = prefix2.replace(/\\/g, "/");
      this._emitMatch(index6, prefix2);
    };
    GlobSync.prototype._stat = function(f) {
      var abs = this._makeAbs(f);
      var needDir = f.slice(-1) === "/";
      if (f.length > this.maxLength)
        return false;
      if (!this.stat && ownProp(this.cache, abs)) {
        var c = this.cache[abs];
        if (Array.isArray(c))
          c = "DIR";
        if (!needDir || c === "DIR")
          return c;
        if (needDir && c === "FILE")
          return false;
      }
      var exists2;
      var stat = this.statCache[abs];
      if (!stat) {
        var lstat;
        try {
          lstat = this.fs.lstatSync(abs);
        } catch (er) {
          if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) {
            this.statCache[abs] = false;
            return false;
          }
        }
        if (lstat && lstat.isSymbolicLink()) {
          try {
            stat = this.fs.statSync(abs);
          } catch (er) {
            stat = lstat;
          }
        } else {
          stat = lstat;
        }
      }
      this.statCache[abs] = stat;
      var c = true;
      if (stat)
        c = stat.isDirectory() ? "DIR" : "FILE";
      this.cache[abs] = this.cache[abs] || c;
      if (needDir && c === "FILE")
        return false;
      return c;
    };
    GlobSync.prototype._mark = function(p) {
      return common.mark(this, p);
    };
    GlobSync.prototype._makeAbs = function(f) {
      return common.makeAbs(this, f);
    };
  }
});

// ../node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js
var require_wrappy = __commonJS({
  "../node_modules/.pnpm/wrappy@1.0.2/node_modules/wrappy/wrappy.js"(exports, module) {
    "use strict";
    module.exports = wrappy;
    function wrappy(fn, cb) {
      if (fn && cb) return wrappy(fn)(cb);
      if (typeof fn !== "function")
        throw new TypeError("need wrapper function");
      Object.keys(fn).forEach(function(k) {
        wrapper[k] = fn[k];
      });
      return wrapper;
      function wrapper() {
        var args = new Array(arguments.length);
        for (var i = 0; i < args.length; i++) {
          args[i] = arguments[i];
        }
        var ret = fn.apply(this, args);
        var cb2 = args[args.length - 1];
        if (typeof ret === "function" && ret !== cb2) {
          Object.keys(cb2).forEach(function(k) {
            ret[k] = cb2[k];
          });
        }
        return ret;
      }
    }
  }
});

// ../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js
var require_once = __commonJS({
  "../node_modules/.pnpm/once@1.4.0/node_modules/once/once.js"(exports, module) {
    "use strict";
    var wrappy = require_wrappy();
    module.exports = wrappy(once);
    module.exports.strict = wrappy(onceStrict);
    once.proto = once(function() {
      Object.defineProperty(Function.prototype, "once", {
        value: function() {
          return once(this);
        },
        configurable: true
      });
      Object.defineProperty(Function.prototype, "onceStrict", {
        value: function() {
          return onceStrict(this);
        },
        configurable: true
      });
    });
    function once(fn) {
      var f = function() {
        if (f.called) return f.value;
        f.called = true;
        return f.value = fn.apply(this, arguments);
      };
      f.called = false;
      return f;
    }
    function onceStrict(fn) {
      var f = function() {
        if (f.called)
          throw new Error(f.onceError);
        f.called = true;
        return f.value = fn.apply(this, arguments);
      };
      var name2 = fn.name || "Function wrapped with `once`";
      f.onceError = name2 + " shouldn't be called more than once";
      f.called = false;
      return f;
    }
  }
});

// ../node_modules/.pnpm/inflight@1.0.6/node_modules/inflight/inflight.js
var require_inflight = __commonJS({
  "../node_modules/.pnpm/inflight@1.0.6/node_modules/inflight/inflight.js"(exports, module) {
    "use strict";
    var wrappy = require_wrappy();
    var reqs = /* @__PURE__ */ Object.create(null);
    var once = require_once();
    module.exports = wrappy(inflight);
    function inflight(key, cb) {
      if (reqs[key]) {
        reqs[key].push(cb);
        return null;
      } else {
        reqs[key] = [cb];
        return makeres(key);
      }
    }
    function makeres(key) {
      return once(function RES() {
        var cbs = reqs[key];
        var len = cbs.length;
        var args = slice(arguments);
        try {
          for (var i = 0; i < len; i++) {
            cbs[i].apply(null, args);
          }
        } finally {
          if (cbs.length > len) {
            cbs.splice(0, len);
            process.nextTick(function() {
              RES.apply(null, args);
            });
          } else {
            delete reqs[key];
          }
        }
      });
    }
    function slice(args) {
      var length = args.length;
      var array2 = [];
      for (var i = 0; i < length; i++) array2[i] = args[i];
      return array2;
    }
  }
});

// ../node_modules/.pnpm/glob@8.1.0/node_modules/glob/glob.js
var require_glob = __commonJS({
  "../node_modules/.pnpm/glob@8.1.0/node_modules/glob/glob.js"(exports, module) {
    "use strict";
    module.exports = glob2;
    var rp = require_fs();
    var minimatch2 = require_minimatch();
    var Minimatch2 = minimatch2.Minimatch;
    var inherits = require_inherits();
    var EE = __require("events").EventEmitter;
    var path2 = __require("path");
    var assert = __require("assert");
    var isAbsolute = __require("path").isAbsolute;
    var globSync = require_sync();
    var common = require_common();
    var setopts = common.setopts;
    var ownProp = common.ownProp;
    var inflight = require_inflight();
    var util2 = __require("util");
    var childrenIgnored = common.childrenIgnored;
    var isIgnored = common.isIgnored;
    var once = require_once();
    function glob2(pattern, options, cb) {
      if (typeof options === "function") cb = options, options = {};
      if (!options) options = {};
      if (options.sync) {
        if (cb)
          throw new TypeError("callback provided to sync glob");
        return globSync(pattern, options);
      }
      return new Glob(pattern, options, cb);
    }
    glob2.sync = globSync;
    var GlobSync = glob2.GlobSync = globSync.GlobSync;
    glob2.glob = glob2;
    function extend(origin, add) {
      if (add === null || typeof add !== "object") {
        return origin;
      }
      var keys = Object.keys(add);
      var i = keys.length;
      while (i--) {
        origin[keys[i]] = add[keys[i]];
      }
      return origin;
    }
    glob2.hasMagic = function(pattern, options_) {
      var options = extend({}, options_);
      options.noprocess = true;
      var g = new Glob(pattern, options);
      var set = g.minimatch.set;
      if (!pattern)
        return false;
      if (set.length > 1)
        return true;
      for (var j = 0; j < set[0].length; j++) {
        if (typeof set[0][j] !== "string")
          return true;
      }
      return false;
    };
    glob2.Glob = Glob;
    inherits(Glob, EE);
    function Glob(pattern, options, cb) {
      if (typeof options === "function") {
        cb = options;
        options = null;
      }
      if (options && options.sync) {
        if (cb)
          throw new TypeError("callback provided to sync glob");
        return new GlobSync(pattern, options);
      }
      if (!(this instanceof Glob))
        return new Glob(pattern, options, cb);
      setopts(this, pattern, options);
      this._didRealPath = false;
      var n = this.minimatch.set.length;
      this.matches = new Array(n);
      if (typeof cb === "function") {
        cb = once(cb);
        this.on("error", cb);
        this.on("end", function(matches) {
          cb(null, matches);
        });
      }
      var self2 = this;
      this._processing = 0;
      this._emitQueue = [];
      this._processQueue = [];
      this.paused = false;
      if (this.noprocess)
        return this;
      if (n === 0)
        return done();
      var sync2 = true;
      for (var i = 0; i < n; i++) {
        this._process(this.minimatch.set[i], i, false, done);
      }
      sync2 = false;
      function done() {
        --self2._processing;
        if (self2._processing <= 0) {
          if (sync2) {
            process.nextTick(function() {
              self2._finish();
            });
          } else {
            self2._finish();
          }
        }
      }
    }
    Glob.prototype._finish = function() {
      assert(this instanceof Glob);
      if (this.aborted)
        return;
      if (this.realpath && !this._didRealpath)
        return this._realpath();
      common.finish(this);
      this.emit("end", this.found);
    };
    Glob.prototype._realpath = function() {
      if (this._didRealpath)
        return;
      this._didRealpath = true;
      var n = this.matches.length;
      if (n === 0)
        return this._finish();
      var self2 = this;
      for (var i = 0; i < this.matches.length; i++)
        this._realpathSet(i, next);
      function next() {
        if (--n === 0)
          self2._finish();
      }
    };
    Glob.prototype._realpathSet = function(index6, cb) {
      var matchset = this.matches[index6];
      if (!matchset)
        return cb();
      var found = Object.keys(matchset);
      var self2 = this;
      var n = found.length;
      if (n === 0)
        return cb();
      var set = this.matches[index6] = /* @__PURE__ */ Object.create(null);
      found.forEach(function(p, i) {
        p = self2._makeAbs(p);
        rp.realpath(p, self2.realpathCache, function(er, real5) {
          if (!er)
            set[real5] = true;
          else if (er.syscall === "stat")
            set[p] = true;
          else
            self2.emit("error", er);
          if (--n === 0) {
            self2.matches[index6] = set;
            cb();
          }
        });
      });
    };
    Glob.prototype._mark = function(p) {
      return common.mark(this, p);
    };
    Glob.prototype._makeAbs = function(f) {
      return common.makeAbs(this, f);
    };
    Glob.prototype.abort = function() {
      this.aborted = true;
      this.emit("abort");
    };
    Glob.prototype.pause = function() {
      if (!this.paused) {
        this.paused = true;
        this.emit("pause");
      }
    };
    Glob.prototype.resume = function() {
      if (this.paused) {
        this.emit("resume");
        this.paused = false;
        if (this._emitQueue.length) {
          var eq2 = this._emitQueue.slice(0);
          this._emitQueue.length = 0;
          for (var i = 0; i < eq2.length; i++) {
            var e = eq2[i];
            this._emitMatch(e[0], e[1]);
          }
        }
        if (this._processQueue.length) {
          var pq = this._processQueue.slice(0);
          this._processQueue.length = 0;
          for (var i = 0; i < pq.length; i++) {
            var p = pq[i];
            this._processing--;
            this._process(p[0], p[1], p[2], p[3]);
          }
        }
      }
    };
    Glob.prototype._process = function(pattern, index6, inGlobStar, cb) {
      assert(this instanceof Glob);
      assert(typeof cb === "function");
      if (this.aborted)
        return;
      this._processing++;
      if (this.paused) {
        this._processQueue.push([pattern, index6, inGlobStar, cb]);
        return;
      }
      var n = 0;
      while (typeof pattern[n] === "string") {
        n++;
      }
      var prefix2;
      switch (n) {
        // if not, then this is rather simple
        case pattern.length:
          this._processSimple(pattern.join("/"), index6, cb);
          return;
        case 0:
          prefix2 = null;
          break;
        default:
          prefix2 = pattern.slice(0, n).join("/");
          break;
      }
      var remain = pattern.slice(n);
      var read;
      if (prefix2 === null)
        read = ".";
      else if (isAbsolute(prefix2) || isAbsolute(pattern.map(function(p) {
        return typeof p === "string" ? p : "[*]";
      }).join("/"))) {
        if (!prefix2 || !isAbsolute(prefix2))
          prefix2 = "/" + prefix2;
        read = prefix2;
      } else
        read = prefix2;
      var abs = this._makeAbs(read);
      if (childrenIgnored(this, read))
        return cb();
      var isGlobStar = remain[0] === minimatch2.GLOBSTAR;
      if (isGlobStar)
        this._processGlobStar(prefix2, read, abs, remain, index6, inGlobStar, cb);
      else
        this._processReaddir(prefix2, read, abs, remain, index6, inGlobStar, cb);
    };
    Glob.prototype._processReaddir = function(prefix2, read, abs, remain, index6, inGlobStar, cb) {
      var self2 = this;
      this._readdir(abs, inGlobStar, function(er, entries) {
        return self2._processReaddir2(prefix2, read, abs, remain, index6, inGlobStar, entries, cb);
      });
    };
    Glob.prototype._processReaddir2 = function(prefix2, read, abs, remain, index6, inGlobStar, entries, cb) {
      if (!entries)
        return cb();
      var pn = remain[0];
      var negate = !!this.minimatch.negate;
      var rawGlob = pn._glob;
      var dotOk = this.dot || rawGlob.charAt(0) === ".";
      var matchedEntries = [];
      for (var i = 0; i < entries.length; i++) {
        var e = entries[i];
        if (e.charAt(0) !== "." || dotOk) {
          var m;
          if (negate && !prefix2) {
            m = !e.match(pn);
          } else {
            m = e.match(pn);
          }
          if (m)
            matchedEntries.push(e);
        }
      }
      var len = matchedEntries.length;
      if (len === 0)
        return cb();
      if (remain.length === 1 && !this.mark && !this.stat) {
        if (!this.matches[index6])
          this.matches[index6] = /* @__PURE__ */ Object.create(null);
        for (var i = 0; i < len; i++) {
          var e = matchedEntries[i];
          if (prefix2) {
            if (prefix2 !== "/")
              e = prefix2 + "/" + e;
            else
              e = prefix2 + e;
          }
          if (e.charAt(0) === "/" && !this.nomount) {
            e = path2.join(this.root, e);
          }
          this._emitMatch(index6, e);
        }
        return cb();
      }
      remain.shift();
      for (var i = 0; i < len; i++) {
        var e = matchedEntries[i];
        var newPattern;
        if (prefix2) {
          if (prefix2 !== "/")
            e = prefix2 + "/" + e;
          else
            e = prefix2 + e;
        }
        this._process([e].concat(remain), index6, inGlobStar, cb);
      }
      cb();
    };
    Glob.prototype._emitMatch = function(index6, e) {
      if (this.aborted)
        return;
      if (isIgnored(this, e))
        return;
      if (this.paused) {
        this._emitQueue.push([index6, e]);
        return;
      }
      var abs = isAbsolute(e) ? e : this._makeAbs(e);
      if (this.mark)
        e = this._mark(e);
      if (this.absolute)
        e = abs;
      if (this.matches[index6][e])
        return;
      if (this.nodir) {
        var c = this.cache[abs];
        if (c === "DIR" || Array.isArray(c))
          return;
      }
      this.matches[index6][e] = true;
      var st = this.statCache[abs];
      if (st)
        this.emit("stat", e, st);
      this.emit("match", e);
    };
    Glob.prototype._readdirInGlobStar = function(abs, cb) {
      if (this.aborted)
        return;
      if (this.follow)
        return this._readdir(abs, false, cb);
      var lstatkey = "lstat\0" + abs;
      var self2 = this;
      var lstatcb = inflight(lstatkey, lstatcb_);
      if (lstatcb)
        self2.fs.lstat(abs, lstatcb);
      function lstatcb_(er, lstat) {
        if (er && er.code === "ENOENT")
          return cb();
        var isSym = lstat && lstat.isSymbolicLink();
        self2.symlinks[abs] = isSym;
        if (!isSym && lstat && !lstat.isDirectory()) {
          self2.cache[abs] = "FILE";
          cb();
        } else
          self2._readdir(abs, false, cb);
      }
    };
    Glob.prototype._readdir = function(abs, inGlobStar, cb) {
      if (this.aborted)
        return;
      cb = inflight("readdir\0" + abs + "\0" + inGlobStar, cb);
      if (!cb)
        return;
      if (inGlobStar && !ownProp(this.symlinks, abs))
        return this._readdirInGlobStar(abs, cb);
      if (ownProp(this.cache, abs)) {
        var c = this.cache[abs];
        if (!c || c === "FILE")
          return cb();
        if (Array.isArray(c))
          return cb(null, c);
      }
      var self2 = this;
      self2.fs.readdir(abs, readdirCb(this, abs, cb));
    };
    function readdirCb(self2, abs, cb) {
      return function(er, entries) {
        if (er)
          self2._readdirError(abs, er, cb);
        else
          self2._readdirEntries(abs, entries, cb);
      };
    }
    Glob.prototype._readdirEntries = function(abs, entries, cb) {
      if (this.aborted)
        return;
      if (!this.mark && !this.stat) {
        for (var i = 0; i < entries.length; i++) {
          var e = entries[i];
          if (abs === "/")
            e = abs + e;
          else
            e = abs + "/" + e;
          this.cache[e] = true;
        }
      }
      this.cache[abs] = entries;
      return cb(null, entries);
    };
    Glob.prototype._readdirError = function(f, er, cb) {
      if (this.aborted)
        return;
      switch (er.code) {
        case "ENOTSUP":
        // https://github.com/isaacs/node-glob/issues/205
        case "ENOTDIR":
          var abs = this._makeAbs(f);
          this.cache[abs] = "FILE";
          if (abs === this.cwdAbs) {
            var error2 = new Error(er.code + " invalid cwd " + this.cwd);
            error2.path = this.cwd;
            error2.code = er.code;
            this.emit("error", error2);
            this.abort();
          }
          break;
        case "ENOENT":
        // not terribly unusual
        case "ELOOP":
        case "ENAMETOOLONG":
        case "UNKNOWN":
          this.cache[this._makeAbs(f)] = false;
          break;
        default:
          this.cache[this._makeAbs(f)] = false;
          if (this.strict) {
            this.emit("error", er);
            this.abort();
          }
          if (!this.silent)
            console.error("glob error", er);
          break;
      }
      return cb();
    };
    Glob.prototype._processGlobStar = function(prefix2, read, abs, remain, index6, inGlobStar, cb) {
      var self2 = this;
      this._readdir(abs, inGlobStar, function(er, entries) {
        self2._processGlobStar2(prefix2, read, abs, remain, index6, inGlobStar, entries, cb);
      });
    };
    Glob.prototype._processGlobStar2 = function(prefix2, read, abs, remain, index6, inGlobStar, entries, cb) {
      if (!entries)
        return cb();
      var remainWithoutGlobStar = remain.slice(1);
      var gspref = prefix2 ? [prefix2] : [];
      var noGlobStar = gspref.concat(remainWithoutGlobStar);
      this._process(noGlobStar, index6, false, cb);
      var isSym = this.symlinks[abs];
      var len = entries.length;
      if (isSym && inGlobStar)
        return cb();
      for (var i = 0; i < len; i++) {
        var e = entries[i];
        if (e.charAt(0) === "." && !this.dot)
          continue;
        var instead = gspref.concat(entries[i], remainWithoutGlobStar);
        this._process(instead, index6, true, cb);
        var below = gspref.concat(entries[i], remain);
        this._process(below, index6, true, cb);
      }
      cb();
    };
    Glob.prototype._processSimple = function(prefix2, index6, cb) {
      var self2 = this;
      this._stat(prefix2, function(er, exists2) {
        self2._processSimple2(prefix2, index6, er, exists2, cb);
      });
    };
    Glob.prototype._processSimple2 = function(prefix2, index6, er, exists2, cb) {
      if (!this.matches[index6])
        this.matches[index6] = /* @__PURE__ */ Object.create(null);
      if (!exists2)
        return cb();
      if (prefix2 && isAbsolute(prefix2) && !this.nomount) {
        var trail = /[\/\\]$/.test(prefix2);
        if (prefix2.charAt(0) === "/") {
          prefix2 = path2.join(this.root, prefix2);
        } else {
          prefix2 = path2.resolve(this.root, prefix2);
          if (trail)
            prefix2 += "/";
        }
      }
      if (process.platform === "win32")
        prefix2 = prefix2.replace(/\\/g, "/");
      this._emitMatch(index6, prefix2);
      cb();
    };
    Glob.prototype._stat = function(f, cb) {
      var abs = this._makeAbs(f);
      var needDir = f.slice(-1) === "/";
      if (f.length > this.maxLength)
        return cb();
      if (!this.stat && ownProp(this.cache, abs)) {
        var c = this.cache[abs];
        if (Array.isArray(c))
          c = "DIR";
        if (!needDir || c === "DIR")
          return cb(null, c);
        if (needDir && c === "FILE")
          return cb();
      }
      var exists2;
      var stat = this.statCache[abs];
      if (stat !== void 0) {
        if (stat === false)
          return cb(null, stat);
        else {
          var type = stat.isDirectory() ? "DIR" : "FILE";
          if (needDir && type === "FILE")
            return cb();
          else
            return cb(null, type, stat);
        }
      }
      var self2 = this;
      var statcb = inflight("stat\0" + abs, lstatcb_);
      if (statcb)
        self2.fs.lstat(abs, statcb);
      function lstatcb_(er, lstat) {
        if (lstat && lstat.isSymbolicLink()) {
          return self2.fs.stat(abs, function(er2, stat2) {
            if (er2)
              self2._stat2(f, abs, null, lstat, cb);
            else
              self2._stat2(f, abs, er2, stat2, cb);
          });
        } else {
          self2._stat2(f, abs, er, lstat, cb);
        }
      }
    };
    Glob.prototype._stat2 = function(f, abs, er, stat, cb) {
      if (er && (er.code === "ENOENT" || er.code === "ENOTDIR")) {
        this.statCache[abs] = false;
        return cb();
      }
      var needDir = f.slice(-1) === "/";
      this.statCache[abs] = stat;
      if (abs.slice(-1) === "/" && stat && !stat.isDirectory())
        return cb(null, false, stat);
      var c = true;
      if (stat)
        c = stat.isDirectory() ? "DIR" : "FILE";
      this.cache[abs] = this.cache[abs] || c;
      if (needDir && c === "FILE")
        return cb();
      return cb(null, c, stat);
    };
  }
});

// ../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/readline.js
var require_readline = __commonJS({
  "../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/readline.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.prepareReadLine = void 0;
    var prepareReadLine = () => {
      const stdin = process.stdin;
      const stdout = process.stdout;
      const readline = __require("readline");
      const rl = readline.createInterface({
        input: stdin,
        escapeCodeTimeout: 50
      });
      readline.emitKeypressEvents(stdin, rl);
      return {
        stdin,
        stdout,
        closable: rl
      };
    };
    exports.prepareReadLine = prepareReadLine;
  }
});

// ../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js
var require_src = __commonJS({
  "../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports, module) {
    "use strict";
    var ESC = "\x1B";
    var CSI = `${ESC}[`;
    var beep = "\x07";
    var cursor = {
      to(x, y) {
        if (!y) return `${CSI}${x + 1}G`;
        return `${CSI}${y + 1};${x + 1}H`;
      },
      move(x, y) {
        let ret = "";
        if (x < 0) ret += `${CSI}${-x}D`;
        else if (x > 0) ret += `${CSI}${x}C`;
        if (y < 0) ret += `${CSI}${-y}A`;
        else if (y > 0) ret += `${CSI}${y}B`;
        return ret;
      },
      up: (count2 = 1) => `${CSI}${count2}A`,
      down: (count2 = 1) => `${CSI}${count2}B`,
      forward: (count2 = 1) => `${CSI}${count2}C`,
      backward: (count2 = 1) => `${CSI}${count2}D`,
      nextLine: (count2 = 1) => `${CSI}E`.repeat(count2),
      prevLine: (count2 = 1) => `${CSI}F`.repeat(count2),
      left: `${CSI}G`,
      hide: `${CSI}?25l`,
      show: `${CSI}?25h`,
      save: `${ESC}7`,
      restore: `${ESC}8`
    };
    var scroll = {
      up: (count2 = 1) => `${CSI}S`.repeat(count2),
      down: (count2 = 1) => `${CSI}T`.repeat(count2)
    };
    var erase = {
      screen: `${CSI}2J`,
      up: (count2 = 1) => `${CSI}1J`.repeat(count2),
      down: (count2 = 1) => `${CSI}J`.repeat(count2),
      line: `${CSI}2K`,
      lineEnd: `${CSI}K`,
      lineStart: `${CSI}1K`,
      lines(count2) {
        let clear = "";
        for (let i = 0; i < count2; i++)
          clear += this.line + (i < count2 - 1 ? cursor.up() : "");
        if (count2)
          clear += cursor.left;
        return clear;
      }
    };
    module.exports = { cursor, scroll, erase, beep };
  }
});

// ../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/utils.js
var require_utils = __commonJS({
  "../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/utils.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.clear = void 0;
    var sisteransi_1 = require_src();
    var strip = (str) => {
      const pattern = [
        "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
        "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
      ].join("|");
      const RGX = new RegExp(pattern, "g");
      return typeof str === "string" ? str.replace(RGX, "") : str;
    };
    var stringWidth = (str) => [...strip(str)].length;
    var clear = function(prompt, perLine) {
      if (!perLine)
        return sisteransi_1.erase.line + sisteransi_1.cursor.to(0);
      let rows = 0;
      const lines = prompt.split(/\r?\n/);
      for (let line2 of lines) {
        rows += 1 + Math.floor(Math.max(stringWidth(line2) - 1, 0) / perLine);
      }
      return sisteransi_1.erase.lines(rows);
    };
    exports.clear = clear;
  }
});

// ../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js
var require_lodash = __commonJS({
  "../node_modules/.pnpm/lodash.throttle@4.1.1/node_modules/lodash.throttle/index.js"(exports, module) {
    "use strict";
    var FUNC_ERROR_TEXT = "Expected a function";
    var NAN = 0 / 0;
    var symbolTag = "[object Symbol]";
    var reTrim = /^\s+|\s+$/g;
    var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
    var reIsBinary = /^0b[01]+$/i;
    var reIsOctal = /^0o[0-7]+$/i;
    var freeParseInt = parseInt;
    var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
    var freeSelf = typeof self == "object" && self && self.Object === Object && self;
    var root = freeGlobal || freeSelf || Function("return this")();
    var objectProto = Object.prototype;
    var objectToString = objectProto.toString;
    var nativeMax = Math.max;
    var nativeMin = Math.min;
    var now = function() {
      return root.Date.now();
    };
    function debounce(func, wait, options) {
      var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
      if (typeof func != "function") {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      wait = toNumber(wait) || 0;
      if (isObject(options)) {
        leading = !!options.leading;
        maxing = "maxWait" in options;
        maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
        trailing = "trailing" in options ? !!options.trailing : trailing;
      }
      function invokeFunc(time4) {
        var args = lastArgs, thisArg = lastThis;
        lastArgs = lastThis = void 0;
        lastInvokeTime = time4;
        result = func.apply(thisArg, args);
        return result;
      }
      function leadingEdge(time4) {
        lastInvokeTime = time4;
        timerId = setTimeout(timerExpired, wait);
        return leading ? invokeFunc(time4) : result;
      }
      function remainingWait(time4) {
        var timeSinceLastCall = time4 - lastCallTime, timeSinceLastInvoke = time4 - lastInvokeTime, result2 = wait - timeSinceLastCall;
        return maxing ? nativeMin(result2, maxWait - timeSinceLastInvoke) : result2;
      }
      function shouldInvoke(time4) {
        var timeSinceLastCall = time4 - lastCallTime, timeSinceLastInvoke = time4 - lastInvokeTime;
        return lastCallTime === void 0 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
      }
      function timerExpired() {
        var time4 = now();
        if (shouldInvoke(time4)) {
          return trailingEdge(time4);
        }
        timerId = setTimeout(timerExpired, remainingWait(time4));
      }
      function trailingEdge(time4) {
        timerId = void 0;
        if (trailing && lastArgs) {
          return invokeFunc(time4);
        }
        lastArgs = lastThis = void 0;
        return result;
      }
      function cancel() {
        if (timerId !== void 0) {
          clearTimeout(timerId);
        }
        lastInvokeTime = 0;
        lastArgs = lastCallTime = lastThis = timerId = void 0;
      }
      function flush() {
        return timerId === void 0 ? result : trailingEdge(now());
      }
      function debounced() {
        var time4 = now(), isInvoking = shouldInvoke(time4);
        lastArgs = arguments;
        lastThis = this;
        lastCallTime = time4;
        if (isInvoking) {
          if (timerId === void 0) {
            return leadingEdge(lastCallTime);
          }
          if (maxing) {
            timerId = setTimeout(timerExpired, wait);
            return invokeFunc(lastCallTime);
          }
        }
        if (timerId === void 0) {
          timerId = setTimeout(timerExpired, wait);
        }
        return result;
      }
      debounced.cancel = cancel;
      debounced.flush = flush;
      return debounced;
    }
    function throttle(func, wait, options) {
      var leading = true, trailing = true;
      if (typeof func != "function") {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      if (isObject(options)) {
        leading = "leading" in options ? !!options.leading : leading;
        trailing = "trailing" in options ? !!options.trailing : trailing;
      }
      return debounce(func, wait, {
        "leading": leading,
        "maxWait": wait,
        "trailing": trailing
      });
    }
    function isObject(value) {
      var type = typeof value;
      return !!value && (type == "object" || type == "function");
    }
    function isObjectLike(value) {
      return !!value && typeof value == "object";
    }
    function isSymbol(value) {
      return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
    }
    function toNumber(value) {
      if (typeof value == "number") {
        return value;
      }
      if (isSymbol(value)) {
        return NAN;
      }
      if (isObject(value)) {
        var other = typeof value.valueOf == "function" ? value.valueOf() : value;
        value = isObject(other) ? other + "" : other;
      }
      if (typeof value != "string") {
        return value === 0 ? value : +value;
      }
      value = value.replace(reTrim, "");
      var isBinary = reIsBinary.test(value);
      return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
    }
    module.exports = throttle;
  }
});

// ../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js
var require_hanji = __commonJS({
  "../node_modules/.pnpm/hanji@0.0.5/node_modules/hanji/index.js"(exports) {
    "use strict";
    var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
      function adopt(value) {
        return value instanceof P ? value : new P(function(resolve) {
          resolve(value);
        });
      }
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e) {
            reject(e);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e) {
            reject(e);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    var __importDefault = exports && exports.__importDefault || function(mod) {
      return mod && mod.__esModule ? mod : { "default": mod };
    };
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.onTerminate = exports.renderWithTask = exports.render = exports.TaskTerminal = exports.TaskView = exports.Terminal = exports.deferred = exports.SelectState = exports.Prompt = void 0;
    var readline_1 = require_readline();
    var sisteransi_1 = require_src();
    var utils_1 = require_utils();
    var lodash_throttle_1 = __importDefault(require_lodash());
    var Prompt3 = class {
      constructor() {
        this.attachCallbacks = [];
        this.detachCallbacks = [];
        this.inputCallbacks = [];
      }
      requestLayout() {
        this.terminal.requestLayout();
      }
      on(type, callback) {
        if (type === "attach") {
          this.attachCallbacks.push(callback);
        } else if (type === "detach") {
          this.detachCallbacks.push(callback);
        } else if (type === "input") {
          this.inputCallbacks.push(callback);
        }
      }
      attach(terminal) {
        this.terminal = terminal;
        this.attachCallbacks.forEach((it) => it(terminal));
      }
      detach(terminal) {
        this.detachCallbacks.forEach((it) => it(terminal));
        this.terminal = void 0;
      }
      input(str, key) {
        this.inputCallbacks.forEach((it) => it(str, key));
      }
    };
    exports.Prompt = Prompt3;
    var SelectState3 = class {
      constructor(items) {
        this.items = items;
        this.selectedIdx = 0;
      }
      bind(prompt) {
        prompt.on("input", (str, key) => {
          const invalidate = this.consume(str, key);
          if (invalidate)
            prompt.requestLayout();
        });
      }
      consume(str, key) {
        if (!key)
          return false;
        if (key.name === "down") {
          this.selectedIdx = (this.selectedIdx + 1) % this.items.length;
          return true;
        }
        if (key.name === "up") {
          this.selectedIdx -= 1;
          this.selectedIdx = this.selectedIdx < 0 ? this.items.length - 1 : this.selectedIdx;
          return true;
        }
        return false;
      }
    };
    exports.SelectState = SelectState3;
    var deferred = () => {
      let resolve;
      let reject;
      const promise = new Promise((res, rej) => {
        resolve = res;
        reject = rej;
      });
      return {
        resolve,
        reject,
        promise
      };
    };
    exports.deferred = deferred;
    var Terminal = class {
      constructor(view5, stdin, stdout, closable) {
        this.view = view5;
        this.stdin = stdin;
        this.stdout = stdout;
        this.closable = closable;
        this.text = "";
        this.status = "idle";
        if (this.stdin.isTTY)
          this.stdin.setRawMode(true);
        const keypress = (str, key) => {
          if (key.name === "c" && key.ctrl === true) {
            this.requestLayout();
            this.view.detach(this);
            this.tearDown(keypress);
            if (terminateHandler) {
              terminateHandler(this.stdin, this.stdout);
              return;
            }
            this.stdout.write(`
^C
`);
            process.exit(1);
          }
          if (key.name === "escape") {
            this.status = "aborted";
            this.requestLayout();
            this.view.detach(this);
            this.tearDown(keypress);
            this.resolve({ status: "aborted", data: void 0 });
            return;
          }
          if (key.name === "return") {
            this.status = "submitted";
            this.requestLayout();
            this.view.detach(this);
            this.tearDown(keypress);
            this.resolve({ status: "submitted", data: this.view.result() });
            return;
          }
          view5.input(str, key);
        };
        this.stdin.on("keypress", keypress);
        this.view.attach(this);
        const { resolve, promise } = (0, exports.deferred)();
        this.resolve = resolve;
        this.promise = promise;
        this.renderFunc = (0, lodash_throttle_1.default)((str) => {
          this.stdout.write(str);
        });
      }
      tearDown(keypress) {
        this.stdout.write(sisteransi_1.cursor.show);
        this.stdin.removeListener("keypress", keypress);
        if (this.stdin.isTTY)
          this.stdin.setRawMode(false);
        this.closable.close();
      }
      result() {
        return this.promise;
      }
      toggleCursor(state) {
        if (state === "hide") {
          this.stdout.write(sisteransi_1.cursor.hide);
        } else {
          this.stdout.write(sisteransi_1.cursor.show);
        }
      }
      requestLayout() {
        const string = this.view.render(this.status);
        const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
        this.text = string;
        this.renderFunc(`${clearPrefix}${string}`);
      }
    };
    exports.Terminal = Terminal;
    var TaskView2 = class {
      constructor() {
        this.attachCallbacks = [];
        this.detachCallbacks = [];
      }
      requestLayout() {
        this.terminal.requestLayout();
      }
      attach(terminal) {
        this.terminal = terminal;
        this.attachCallbacks.forEach((it) => it(terminal));
      }
      detach(terminal) {
        this.detachCallbacks.forEach((it) => it(terminal));
        this.terminal = void 0;
      }
      on(type, callback) {
        if (type === "attach") {
          this.attachCallbacks.push(callback);
        } else if (type === "detach") {
          this.detachCallbacks.push(callback);
        }
      }
    };
    exports.TaskView = TaskView2;
    var TaskTerminal = class {
      constructor(view5, stdout) {
        this.view = view5;
        this.stdout = stdout;
        this.text = "";
        this.view.attach(this);
      }
      requestLayout() {
        const string = this.view.render("pending");
        const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
        this.text = string;
        this.stdout.write(`${clearPrefix}${string}`);
      }
      clear() {
        const string = this.view.render("done");
        this.view.detach(this);
        const clearPrefix = this.text ? (0, utils_1.clear)(this.text, this.stdout.columns) : "";
        this.stdout.write(`${clearPrefix}${string}`);
      }
    };
    exports.TaskTerminal = TaskTerminal;
    function render7(view5) {
      const { stdin, stdout, closable } = (0, readline_1.prepareReadLine)();
      if (view5 instanceof Prompt3) {
        const terminal = new Terminal(view5, stdin, stdout, closable);
        terminal.requestLayout();
        return terminal.result();
      }
      stdout.write(`${view5}
`);
      closable.close();
      return;
    }
    exports.render = render7;
    function renderWithTask5(view5, task) {
      return __awaiter(this, void 0, void 0, function* () {
        const terminal = new TaskTerminal(view5, process.stdout);
        terminal.requestLayout();
        const result = yield task;
        terminal.clear();
        return result;
      });
    }
    exports.renderWithTask = renderWithTask5;
    var terminateHandler;
    function onTerminate(callback) {
      terminateHandler = callback;
    }
    exports.onTerminate = onTerminate;
  }
});

// src/global.ts
var originUUID, snapshotVersion, mapValues, mapKeys, mapEntries, customMapEntries;
var init_global = __esm({
  "src/global.ts"() {
    "use strict";
    originUUID = "00000000-0000-0000-0000-000000000000";
    snapshotVersion = "7";
    mapValues = (obj, map) => {
      const result = Object.keys(obj).reduce(function(result2, key) {
        result2[key] = map(obj[key]);
        return result2;
      }, {});
      return result;
    };
    mapKeys = (obj, map) => {
      const result = Object.fromEntries(
        Object.entries(obj).map(([key, val]) => {
          const newKey = map(key, val);
          return [newKey, val];
        })
      );
      return result;
    };
    mapEntries = (obj, map) => {
      const result = Object.fromEntries(
        Object.entries(obj).map(([key, val]) => {
          const [newKey, newVal] = map(key, val);
          return [newKey, newVal];
        })
      );
      return result;
    };
    customMapEntries = (obj, map) => {
      const result = Object.fromEntries(
        Object.entries(obj).map(([key, val]) => {
          const [newKey, newVal] = map(key, val);
          return [newKey, newVal];
        })
      );
      return result;
    };
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/util.js
var util, objectUtil, ZodParsedType, getParsedType;
var init_util = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/util.js"() {
    "use strict";
    (function(util2) {
      util2.assertEqual = (_2) => {
      };
      function assertIs(_arg) {
      }
      util2.assertIs = assertIs;
      function assertNever(_x) {
        throw new Error();
      }
      util2.assertNever = assertNever;
      util2.arrayToEnum = (items) => {
        const obj = {};
        for (const item of items) {
          obj[item] = item;
        }
        return obj;
      };
      util2.getValidEnumValues = (obj) => {
        const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
        const filtered = {};
        for (const k of validKeys) {
          filtered[k] = obj[k];
        }
        return util2.objectValues(filtered);
      };
      util2.objectValues = (obj) => {
        return util2.objectKeys(obj).map(function(e) {
          return obj[e];
        });
      };
      util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
        const keys = [];
        for (const key in object) {
          if (Object.prototype.hasOwnProperty.call(object, key)) {
            keys.push(key);
          }
        }
        return keys;
      };
      util2.find = (arr, checker) => {
        for (const item of arr) {
          if (checker(item))
            return item;
        }
        return void 0;
      };
      util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
      function joinValues(array2, separator = " | ") {
        return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
      }
      util2.joinValues = joinValues;
      util2.jsonStringifyReplacer = (_2, value) => {
        if (typeof value === "bigint") {
          return value.toString();
        }
        return value;
      };
    })(util || (util = {}));
    (function(objectUtil2) {
      objectUtil2.mergeShapes = (first, second) => {
        return {
          ...first,
          ...second
          // second overwrites first
        };
      };
    })(objectUtil || (objectUtil = {}));
    ZodParsedType = util.arrayToEnum([
      "string",
      "nan",
      "number",
      "integer",
      "float",
      "boolean",
      "date",
      "bigint",
      "symbol",
      "function",
      "undefined",
      "null",
      "array",
      "object",
      "unknown",
      "promise",
      "void",
      "never",
      "map",
      "set"
    ]);
    getParsedType = (data) => {
      const t = typeof data;
      switch (t) {
        case "undefined":
          return ZodParsedType.undefined;
        case "string":
          return ZodParsedType.string;
        case "number":
          return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
        case "boolean":
          return ZodParsedType.boolean;
        case "function":
          return ZodParsedType.function;
        case "bigint":
          return ZodParsedType.bigint;
        case "symbol":
          return ZodParsedType.symbol;
        case "object":
          if (Array.isArray(data)) {
            return ZodParsedType.array;
          }
          if (data === null) {
            return ZodParsedType.null;
          }
          if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
            return ZodParsedType.promise;
          }
          if (typeof Map !== "undefined" && data instanceof Map) {
            return ZodParsedType.map;
          }
          if (typeof Set !== "undefined" && data instanceof Set) {
            return ZodParsedType.set;
          }
          if (typeof Date !== "undefined" && data instanceof Date) {
            return ZodParsedType.date;
          }
          return ZodParsedType.object;
        default:
          return ZodParsedType.unknown;
      }
    };
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/ZodError.js
var ZodIssueCode, ZodError;
var init_ZodError = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/ZodError.js"() {
    "use strict";
    init_util();
    ZodIssueCode = util.arrayToEnum([
      "invalid_type",
      "invalid_literal",
      "custom",
      "invalid_union",
      "invalid_union_discriminator",
      "invalid_enum_value",
      "unrecognized_keys",
      "invalid_arguments",
      "invalid_return_type",
      "invalid_date",
      "invalid_string",
      "too_small",
      "too_big",
      "invalid_intersection_types",
      "not_multiple_of",
      "not_finite"
    ]);
    ZodError = class _ZodError extends Error {
      get errors() {
        return this.issues;
      }
      constructor(issues) {
        super();
        this.issues = [];
        this.addIssue = (sub) => {
          this.issues = [...this.issues, sub];
        };
        this.addIssues = (subs = []) => {
          this.issues = [...this.issues, ...subs];
        };
        const actualProto = new.target.prototype;
        if (Object.setPrototypeOf) {
          Object.setPrototypeOf(this, actualProto);
        } else {
          this.__proto__ = actualProto;
        }
        this.name = "ZodError";
        this.issues = issues;
      }
      format(_mapper) {
        const mapper = _mapper || function(issue) {
          return issue.message;
        };
        const fieldErrors = { _errors: [] };
        const processError = (error2) => {
          for (const issue of error2.issues) {
            if (issue.code === "invalid_union") {
              issue.unionErrors.map(processError);
            } else if (issue.code === "invalid_return_type") {
              processError(issue.returnTypeError);
            } else if (issue.code === "invalid_arguments") {
              processError(issue.argumentsError);
            } else if (issue.path.length === 0) {
              fieldErrors._errors.push(mapper(issue));
            } else {
              let curr = fieldErrors;
              let i = 0;
              while (i < issue.path.length) {
                const el = issue.path[i];
                const terminal = i === issue.path.length - 1;
                if (!terminal) {
                  curr[el] = curr[el] || { _errors: [] };
                } else {
                  curr[el] = curr[el] || { _errors: [] };
                  curr[el]._errors.push(mapper(issue));
                }
                curr = curr[el];
                i++;
              }
            }
          }
        };
        processError(this);
        return fieldErrors;
      }
      static assert(value) {
        if (!(value instanceof _ZodError)) {
          throw new Error(`Not a ZodError: ${value}`);
        }
      }
      toString() {
        return this.message;
      }
      get message() {
        return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
      }
      get isEmpty() {
        return this.issues.length === 0;
      }
      flatten(mapper = (issue) => issue.message) {
        const fieldErrors = {};
        const formErrors = [];
        for (const sub of this.issues) {
          if (sub.path.length > 0) {
            fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
            fieldErrors[sub.path[0]].push(mapper(sub));
          } else {
            formErrors.push(mapper(sub));
          }
        }
        return { formErrors, fieldErrors };
      }
      get formErrors() {
        return this.flatten();
      }
    };
    ZodError.create = (issues) => {
      const error2 = new ZodError(issues);
      return error2;
    };
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/locales/en.js
var errorMap, en_default;
var init_en = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/locales/en.js"() {
    "use strict";
    init_ZodError();
    init_util();
    errorMap = (issue, _ctx) => {
      let message;
      switch (issue.code) {
        case ZodIssueCode.invalid_type:
          if (issue.received === ZodParsedType.undefined) {
            message = "Required";
          } else {
            message = `Expected ${issue.expected}, received ${issue.received}`;
          }
          break;
        case ZodIssueCode.invalid_literal:
          message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
          break;
        case ZodIssueCode.unrecognized_keys:
          message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
          break;
        case ZodIssueCode.invalid_union:
          message = `Invalid input`;
          break;
        case ZodIssueCode.invalid_union_discriminator:
          message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
          break;
        case ZodIssueCode.invalid_enum_value:
          message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
          break;
        case ZodIssueCode.invalid_arguments:
          message = `Invalid function arguments`;
          break;
        case ZodIssueCode.invalid_return_type:
          message = `Invalid function return type`;
          break;
        case ZodIssueCode.invalid_date:
          message = `Invalid date`;
          break;
        case ZodIssueCode.invalid_string:
          if (typeof issue.validation === "object") {
            if ("includes" in issue.validation) {
              message = `Invalid input: must include "${issue.validation.includes}"`;
              if (typeof issue.validation.position === "number") {
                message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
              }
            } else if ("startsWith" in issue.validation) {
              message = `Invalid input: must start with "${issue.validation.startsWith}"`;
            } else if ("endsWith" in issue.validation) {
              message = `Invalid input: must end with "${issue.validation.endsWith}"`;
            } else {
              util.assertNever(issue.validation);
            }
          } else if (issue.validation !== "regex") {
            message = `Invalid ${issue.validation}`;
          } else {
            message = "Invalid";
          }
          break;
        case ZodIssueCode.too_small:
          if (issue.type === "array")
            message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
          else if (issue.type === "string")
            message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
          else if (issue.type === "number")
            message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
          else if (issue.type === "date")
            message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
          else
            message = "Invalid input";
          break;
        case ZodIssueCode.too_big:
          if (issue.type === "array")
            message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
          else if (issue.type === "string")
            message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
          else if (issue.type === "number")
            message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
          else if (issue.type === "bigint")
            message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
          else if (issue.type === "date")
            message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
          else
            message = "Invalid input";
          break;
        case ZodIssueCode.custom:
          message = `Invalid input`;
          break;
        case ZodIssueCode.invalid_intersection_types:
          message = `Intersection results could not be merged`;
          break;
        case ZodIssueCode.not_multiple_of:
          message = `Number must be a multiple of ${issue.multipleOf}`;
          break;
        case ZodIssueCode.not_finite:
          message = "Number must be finite";
          break;
        default:
          message = _ctx.defaultError;
          util.assertNever(issue);
      }
      return { message };
    };
    en_default = errorMap;
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/errors.js
function getErrorMap() {
  return overrideErrorMap;
}
var overrideErrorMap;
var init_errors = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/errors.js"() {
    "use strict";
    init_en();
    overrideErrorMap = en_default;
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/parseUtil.js
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      // contextual error map is first priority
      ctx.schemaErrorMap,
      // then schema-bound map if available
      overrideMap,
      // then global override map
      overrideMap === en_default ? void 0 : en_default
      // then global default map
    ].filter((x) => !!x)
  });
  ctx.common.issues.push(issue);
}
var makeIssue, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync;
var init_parseUtil = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/parseUtil.js"() {
    "use strict";
    init_errors();
    init_en();
    makeIssue = (params) => {
      const { data, path: path2, errorMaps, issueData } = params;
      const fullPath = [...path2, ...issueData.path || []];
      const fullIssue = {
        ...issueData,
        path: fullPath
      };
      if (issueData.message !== void 0) {
        return {
          ...issueData,
          path: fullPath,
          message: issueData.message
        };
      }
      let errorMessage = "";
      const maps = errorMaps.filter((m) => !!m).slice().reverse();
      for (const map of maps) {
        errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
      }
      return {
        ...issueData,
        path: fullPath,
        message: errorMessage
      };
    };
    ParseStatus = class _ParseStatus {
      constructor() {
        this.value = "valid";
      }
      dirty() {
        if (this.value === "valid")
          this.value = "dirty";
      }
      abort() {
        if (this.value !== "aborted")
          this.value = "aborted";
      }
      static mergeArray(status, results) {
        const arrayValue = [];
        for (const s of results) {
          if (s.status === "aborted")
            return INVALID;
          if (s.status === "dirty")
            status.dirty();
          arrayValue.push(s.value);
        }
        return { status: status.value, value: arrayValue };
      }
      static async mergeObjectAsync(status, pairs) {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value
          });
        }
        return _ParseStatus.mergeObjectSync(status, syncPairs);
      }
      static mergeObjectSync(status, pairs) {
        const finalObject = {};
        for (const pair of pairs) {
          const { key, value } = pair;
          if (key.status === "aborted")
            return INVALID;
          if (value.status === "aborted")
            return INVALID;
          if (key.status === "dirty")
            status.dirty();
          if (value.status === "dirty")
            status.dirty();
          if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
            finalObject[key.value] = value.value;
          }
        }
        return { status: status.value, value: finalObject };
      }
    };
    INVALID = Object.freeze({
      status: "aborted"
    });
    DIRTY = (value) => ({ status: "dirty", value });
    OK = (value) => ({ status: "valid", value });
    isAborted = (x) => x.status === "aborted";
    isDirty = (x) => x.status === "dirty";
    isValid = (x) => x.status === "valid";
    isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/typeAliases.js
var init_typeAliases = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/typeAliases.js"() {
    "use strict";
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/errorUtil.js
var errorUtil;
var init_errorUtil = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/helpers/errorUtil.js"() {
    "use strict";
    (function(errorUtil2) {
      errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
      errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
    })(errorUtil || (errorUtil = {}));
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/types.js
function processCreateParams(params) {
  if (!params)
    return {};
  const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  if (errorMap2 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap2)
    return { errorMap: errorMap2, description };
  const customMap = (iss, ctx) => {
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message ?? ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: message ?? required_error ?? ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: message ?? invalid_type_error ?? ctx.defaultError };
  };
  return { errorMap: customMap, description };
}
function timeRegexSource(args) {
  let secondsRegexSource = `[0-5]\\d`;
  if (args.precision) {
    secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  }
  const secondsQuantifier = args.precision ? "+" : "?";
  return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
  let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex = `${regex}(${opts.join("|")})`;
  return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version2) {
  if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base64));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if ("typ" in decoded && decoded?.typ !== "JWT")
      return false;
    if (!decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch {
    return false;
  }
}
function isValidCidr(ip, version2) {
  if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}
function floatSafeRemainder(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / 10 ** decCount;
}
function deepPartialify(schema5) {
  if (schema5 instanceof ZodObject) {
    const newShape = {};
    for (const key in schema5.shape) {
      const fieldSchema = schema5.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema5._def,
      shape: () => newShape
    });
  } else if (schema5 instanceof ZodArray) {
    return new ZodArray({
      ...schema5._def,
      type: deepPartialify(schema5.element)
    });
  } else if (schema5 instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema5.unwrap()));
  } else if (schema5 instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema5.unwrap()));
  } else if (schema5 instanceof ZodTuple) {
    return ZodTuple.create(schema5.items.map((item) => deepPartialify(item)));
  } else {
    return schema5;
  }
}
function mergeValues(a, b) {
  const aType = getParsedType(a);
  const bType = getParsedType(b);
  if (a === b) {
    return { valid: true, data: a };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b);
    const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a, ...b };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a[key], b[key]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a.length !== b.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index6 = 0; index6 < a.length; index6++) {
      const itemA = a[index6];
      const itemB = b[index6];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
    return { valid: true, data: a };
  } else {
    return { valid: false };
  }
}
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
var ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, coerce;
var init_types = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/types.js"() {
    "use strict";
    init_ZodError();
    init_errors();
    init_errorUtil();
    init_parseUtil();
    init_util();
    ParseInputLazyPath = class {
      constructor(parent, value, path2, key) {
        this._cachedPath = [];
        this.parent = parent;
        this.data = value;
        this._path = path2;
        this._key = key;
      }
      get path() {
        if (!this._cachedPath.length) {
          if (Array.isArray(this._key)) {
            this._cachedPath.push(...this._path, ...this._key);
          } else {
            this._cachedPath.push(...this._path, this._key);
          }
        }
        return this._cachedPath;
      }
    };
    handleResult = (ctx, result) => {
      if (isValid(result)) {
        return { success: true, data: result.value };
      } else {
        if (!ctx.common.issues.length) {
          throw new Error("Validation failed but no issues detected.");
        }
        return {
          success: false,
          get error() {
            if (this._error)
              return this._error;
            const error2 = new ZodError(ctx.common.issues);
            this._error = error2;
            return this._error;
          }
        };
      }
    };
    ZodType = class {
      get description() {
        return this._def.description;
      }
      _getType(input) {
        return getParsedType(input.data);
      }
      _getOrReturnCtx(input, ctx) {
        return ctx || {
          common: input.parent.common,
          data: input.data,
          parsedType: getParsedType(input.data),
          schemaErrorMap: this._def.errorMap,
          path: input.path,
          parent: input.parent
        };
      }
      _processInputParams(input) {
        return {
          status: new ParseStatus(),
          ctx: {
            common: input.parent.common,
            data: input.data,
            parsedType: getParsedType(input.data),
            schemaErrorMap: this._def.errorMap,
            path: input.path,
            parent: input.parent
          }
        };
      }
      _parseSync(input) {
        const result = this._parse(input);
        if (isAsync(result)) {
          throw new Error("Synchronous parse encountered promise.");
        }
        return result;
      }
      _parseAsync(input) {
        const result = this._parse(input);
        return Promise.resolve(result);
      }
      parse(data, params) {
        const result = this.safeParse(data, params);
        if (result.success)
          return result.data;
        throw result.error;
      }
      safeParse(data, params) {
        const ctx = {
          common: {
            issues: [],
            async: params?.async ?? false,
            contextualErrorMap: params?.errorMap
          },
          path: params?.path || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        const result = this._parseSync({ data, path: ctx.path, parent: ctx });
        return handleResult(ctx, result);
      }
      "~validate"(data) {
        const ctx = {
          common: {
            issues: [],
            async: !!this["~standard"].async
          },
          path: [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        if (!this["~standard"].async) {
          try {
            const result = this._parseSync({ data, path: [], parent: ctx });
            return isValid(result) ? {
              value: result.value
            } : {
              issues: ctx.common.issues
            };
          } catch (err) {
            if (err?.message?.toLowerCase()?.includes("encountered")) {
              this["~standard"].async = true;
            }
            ctx.common = {
              issues: [],
              async: true
            };
          }
        }
        return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        });
      }
      async parseAsync(data, params) {
        const result = await this.safeParseAsync(data, params);
        if (result.success)
          return result.data;
        throw result.error;
      }
      async safeParseAsync(data, params) {
        const ctx = {
          common: {
            issues: [],
            contextualErrorMap: params?.errorMap,
            async: true
          },
          path: params?.path || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
        const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
        return handleResult(ctx, result);
      }
      refine(check, message) {
        const getIssueProperties = (val) => {
          if (typeof message === "string" || typeof message === "undefined") {
            return { message };
          } else if (typeof message === "function") {
            return message(val);
          } else {
            return message;
          }
        };
        return this._refinement((val, ctx) => {
          const result = check(val);
          const setError = () => ctx.addIssue({
            code: ZodIssueCode.custom,
            ...getIssueProperties(val)
          });
          if (typeof Promise !== "undefined" && result instanceof Promise) {
            return result.then((data) => {
              if (!data) {
                setError();
                return false;
              } else {
                return true;
              }
            });
          }
          if (!result) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      refinement(check, refinementData) {
        return this._refinement((val, ctx) => {
          if (!check(val)) {
            ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
            return false;
          } else {
            return true;
          }
        });
      }
      _refinement(refinement) {
        return new ZodEffects({
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "refinement", refinement }
        });
      }
      superRefine(refinement) {
        return this._refinement(refinement);
      }
      constructor(def) {
        this.spa = this.safeParseAsync;
        this._def = def;
        this.parse = this.parse.bind(this);
        this.safeParse = this.safeParse.bind(this);
        this.parseAsync = this.parseAsync.bind(this);
        this.safeParseAsync = this.safeParseAsync.bind(this);
        this.spa = this.spa.bind(this);
        this.refine = this.refine.bind(this);
        this.refinement = this.refinement.bind(this);
        this.superRefine = this.superRefine.bind(this);
        this.optional = this.optional.bind(this);
        this.nullable = this.nullable.bind(this);
        this.nullish = this.nullish.bind(this);
        this.array = this.array.bind(this);
        this.promise = this.promise.bind(this);
        this.or = this.or.bind(this);
        this.and = this.and.bind(this);
        this.transform = this.transform.bind(this);
        this.brand = this.brand.bind(this);
        this.default = this.default.bind(this);
        this.catch = this.catch.bind(this);
        this.describe = this.describe.bind(this);
        this.pipe = this.pipe.bind(this);
        this.readonly = this.readonly.bind(this);
        this.isNullable = this.isNullable.bind(this);
        this.isOptional = this.isOptional.bind(this);
        this["~standard"] = {
          version: 1,
          vendor: "zod",
          validate: (data) => this["~validate"](data)
        };
      }
      optional() {
        return ZodOptional.create(this, this._def);
      }
      nullable() {
        return ZodNullable.create(this, this._def);
      }
      nullish() {
        return this.nullable().optional();
      }
      array() {
        return ZodArray.create(this);
      }
      promise() {
        return ZodPromise.create(this, this._def);
      }
      or(option) {
        return ZodUnion.create([this, option], this._def);
      }
      and(incoming) {
        return ZodIntersection.create(this, incoming, this._def);
      }
      transform(transform) {
        return new ZodEffects({
          ...processCreateParams(this._def),
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "transform", transform }
        });
      }
      default(def) {
        const defaultValueFunc = typeof def === "function" ? def : () => def;
        return new ZodDefault({
          ...processCreateParams(this._def),
          innerType: this,
          defaultValue: defaultValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodDefault
        });
      }
      brand() {
        return new ZodBranded({
          typeName: ZodFirstPartyTypeKind.ZodBranded,
          type: this,
          ...processCreateParams(this._def)
        });
      }
      catch(def) {
        const catchValueFunc = typeof def === "function" ? def : () => def;
        return new ZodCatch({
          ...processCreateParams(this._def),
          innerType: this,
          catchValue: catchValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodCatch
        });
      }
      describe(description) {
        const This = this.constructor;
        return new This({
          ...this._def,
          description
        });
      }
      pipe(target) {
        return ZodPipeline.create(this, target);
      }
      readonly() {
        return ZodReadonly.create(this);
      }
      isOptional() {
        return this.safeParse(void 0).success;
      }
      isNullable() {
        return this.safeParse(null).success;
      }
    };
    cuidRegex = /^c[^\s-]{8,}$/i;
    cuid2Regex = /^[0-9a-z]+$/;
    ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
    uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
    nanoidRegex = /^[a-z0-9_-]{21}$/i;
    jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
    durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
    emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
    _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
    ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
    ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
    ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
    ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
    base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
    base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
    dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
    dateRegex = new RegExp(`^${dateRegexSource}$`);
    ZodString = class _ZodString extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = String(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.string) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.string,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        const status = new ParseStatus();
        let ctx = void 0;
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            if (input.data.length < check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            if (input.data.length > check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "length") {
            const tooBig = input.data.length > check.value;
            const tooSmall = input.data.length < check.value;
            if (tooBig || tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              if (tooBig) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_big,
                  maximum: check.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check.message
                });
              } else if (tooSmall) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_small,
                  minimum: check.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check.message
                });
              }
              status.dirty();
            }
          } else if (check.kind === "email") {
            if (!emailRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "email",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "emoji") {
            if (!emojiRegex) {
              emojiRegex = new RegExp(_emojiRegex, "u");
            }
            if (!emojiRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "emoji",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "uuid") {
            if (!uuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "uuid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "nanoid") {
            if (!nanoidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "nanoid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cuid") {
            if (!cuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cuid2") {
            if (!cuid2Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid2",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "ulid") {
            if (!ulidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ulid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "url") {
            try {
              new URL(input.data);
            } catch {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "url",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "regex") {
            check.regex.lastIndex = 0;
            const testResult = check.regex.test(input.data);
            if (!testResult) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "regex",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "trim") {
            input.data = input.data.trim();
          } else if (check.kind === "includes") {
            if (!input.data.includes(check.value, check.position)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { includes: check.value, position: check.position },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "toLowerCase") {
            input.data = input.data.toLowerCase();
          } else if (check.kind === "toUpperCase") {
            input.data = input.data.toUpperCase();
          } else if (check.kind === "startsWith") {
            if (!input.data.startsWith(check.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { startsWith: check.value },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "endsWith") {
            if (!input.data.endsWith(check.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { endsWith: check.value },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "datetime") {
            const regex = datetimeRegex(check);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "datetime",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "date") {
            const regex = dateRegex;
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "date",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "time") {
            const regex = timeRegex(check);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "time",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "duration") {
            if (!durationRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "duration",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "ip") {
            if (!isValidIP(input.data, check.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ip",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "jwt") {
            if (!isValidJWT(input.data, check.alg)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "jwt",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cidr") {
            if (!isValidCidr(input.data, check.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cidr",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "base64") {
            if (!base64Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "base64url") {
            if (!base64urlRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64url",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      _regex(regex, validation, message) {
        return this.refinement((data) => regex.test(data), {
          validation,
          code: ZodIssueCode.invalid_string,
          ...errorUtil.errToObj(message)
        });
      }
      _addCheck(check) {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      email(message) {
        return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
      }
      url(message) {
        return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
      }
      emoji(message) {
        return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
      }
      uuid(message) {
        return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
      }
      nanoid(message) {
        return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
      }
      cuid(message) {
        return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
      }
      cuid2(message) {
        return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
      }
      ulid(message) {
        return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
      }
      base64(message) {
        return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
      }
      base64url(message) {
        return this._addCheck({
          kind: "base64url",
          ...errorUtil.errToObj(message)
        });
      }
      jwt(options) {
        return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
      }
      ip(options) {
        return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
      }
      cidr(options) {
        return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
      }
      datetime(options) {
        if (typeof options === "string") {
          return this._addCheck({
            kind: "datetime",
            precision: null,
            offset: false,
            local: false,
            message: options
          });
        }
        return this._addCheck({
          kind: "datetime",
          precision: typeof options?.precision === "undefined" ? null : options?.precision,
          offset: options?.offset ?? false,
          local: options?.local ?? false,
          ...errorUtil.errToObj(options?.message)
        });
      }
      date(message) {
        return this._addCheck({ kind: "date", message });
      }
      time(options) {
        if (typeof options === "string") {
          return this._addCheck({
            kind: "time",
            precision: null,
            message: options
          });
        }
        return this._addCheck({
          kind: "time",
          precision: typeof options?.precision === "undefined" ? null : options?.precision,
          ...errorUtil.errToObj(options?.message)
        });
      }
      duration(message) {
        return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
      }
      regex(regex, message) {
        return this._addCheck({
          kind: "regex",
          regex,
          ...errorUtil.errToObj(message)
        });
      }
      includes(value, options) {
        return this._addCheck({
          kind: "includes",
          value,
          position: options?.position,
          ...errorUtil.errToObj(options?.message)
        });
      }
      startsWith(value, message) {
        return this._addCheck({
          kind: "startsWith",
          value,
          ...errorUtil.errToObj(message)
        });
      }
      endsWith(value, message) {
        return this._addCheck({
          kind: "endsWith",
          value,
          ...errorUtil.errToObj(message)
        });
      }
      min(minLength, message) {
        return this._addCheck({
          kind: "min",
          value: minLength,
          ...errorUtil.errToObj(message)
        });
      }
      max(maxLength, message) {
        return this._addCheck({
          kind: "max",
          value: maxLength,
          ...errorUtil.errToObj(message)
        });
      }
      length(len, message) {
        return this._addCheck({
          kind: "length",
          value: len,
          ...errorUtil.errToObj(message)
        });
      }
      /**
       * Equivalent to `.min(1)`
       */
      nonempty(message) {
        return this.min(1, errorUtil.errToObj(message));
      }
      trim() {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "trim" }]
        });
      }
      toLowerCase() {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "toLowerCase" }]
        });
      }
      toUpperCase() {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "toUpperCase" }]
        });
      }
      get isDatetime() {
        return !!this._def.checks.find((ch) => ch.kind === "datetime");
      }
      get isDate() {
        return !!this._def.checks.find((ch) => ch.kind === "date");
      }
      get isTime() {
        return !!this._def.checks.find((ch) => ch.kind === "time");
      }
      get isDuration() {
        return !!this._def.checks.find((ch) => ch.kind === "duration");
      }
      get isEmail() {
        return !!this._def.checks.find((ch) => ch.kind === "email");
      }
      get isURL() {
        return !!this._def.checks.find((ch) => ch.kind === "url");
      }
      get isEmoji() {
        return !!this._def.checks.find((ch) => ch.kind === "emoji");
      }
      get isUUID() {
        return !!this._def.checks.find((ch) => ch.kind === "uuid");
      }
      get isNANOID() {
        return !!this._def.checks.find((ch) => ch.kind === "nanoid");
      }
      get isCUID() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid");
      }
      get isCUID2() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid2");
      }
      get isULID() {
        return !!this._def.checks.find((ch) => ch.kind === "ulid");
      }
      get isIP() {
        return !!this._def.checks.find((ch) => ch.kind === "ip");
      }
      get isCIDR() {
        return !!this._def.checks.find((ch) => ch.kind === "cidr");
      }
      get isBase64() {
        return !!this._def.checks.find((ch) => ch.kind === "base64");
      }
      get isBase64url() {
        return !!this._def.checks.find((ch) => ch.kind === "base64url");
      }
      get minLength() {
        let min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          }
        }
        return min2;
      }
      get maxLength() {
        let max2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max2 === null || ch.value < max2)
              max2 = ch.value;
          }
        }
        return max2;
      }
    };
    ZodString.create = (params) => {
      return new ZodString({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodString,
        coerce: params?.coerce ?? false,
        ...processCreateParams(params)
      });
    };
    ZodNumber = class _ZodNumber extends ZodType {
      constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
        this.step = this.multipleOf;
      }
      _parse(input) {
        if (this._def.coerce) {
          input.data = Number(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.number) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.number,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check of this._def.checks) {
          if (check.kind === "int") {
            if (!util.isInteger(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: "integer",
                received: "float",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "min") {
            const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check.value,
                type: "number",
                inclusive: check.inclusive,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check.value,
                type: "number",
                inclusive: check.inclusive,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "multipleOf") {
            if (floatSafeRemainder(input.data, check.value) !== 0) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check.value,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "finite") {
            if (!Number.isFinite(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_finite,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodNumber({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check) {
        return new _ZodNumber({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      int(message) {
        return this._addCheck({
          kind: "int",
          message: errorUtil.toString(message)
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      finite(message) {
        return this._addCheck({
          kind: "finite",
          message: errorUtil.toString(message)
        });
      }
      safe(message) {
        return this._addCheck({
          kind: "min",
          inclusive: true,
          value: Number.MIN_SAFE_INTEGER,
          message: errorUtil.toString(message)
        })._addCheck({
          kind: "max",
          inclusive: true,
          value: Number.MAX_SAFE_INTEGER,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          }
        }
        return min2;
      }
      get maxValue() {
        let max2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max2 === null || ch.value < max2)
              max2 = ch.value;
          }
        }
        return max2;
      }
      get isInt() {
        return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
      }
      get isFinite() {
        let max2 = null;
        let min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
            return true;
          } else if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          } else if (ch.kind === "max") {
            if (max2 === null || ch.value < max2)
              max2 = ch.value;
          }
        }
        return Number.isFinite(min2) && Number.isFinite(max2);
      }
    };
    ZodNumber.create = (params) => {
      return new ZodNumber({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodNumber,
        coerce: params?.coerce || false,
        ...processCreateParams(params)
      });
    };
    ZodBigInt = class _ZodBigInt extends ZodType {
      constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
      }
      _parse(input) {
        if (this._def.coerce) {
          try {
            input.data = BigInt(input.data);
          } catch {
            return this._getInvalidInput(input);
          }
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.bigint) {
          return this._getInvalidInput(input);
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                type: "bigint",
                minimum: check.value,
                inclusive: check.inclusive,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                type: "bigint",
                maximum: check.value,
                inclusive: check.inclusive,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "multipleOf") {
            if (input.data % check.value !== BigInt(0)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check.value,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      _getInvalidInput(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_type,
          expected: ZodParsedType.bigint,
          received: ctx.parsedType
        });
        return INVALID;
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodBigInt({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check) {
        return new _ZodBigInt({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          }
        }
        return min2;
      }
      get maxValue() {
        let max2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max2 === null || ch.value < max2)
              max2 = ch.value;
          }
        }
        return max2;
      }
    };
    ZodBigInt.create = (params) => {
      return new ZodBigInt({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodBigInt,
        coerce: params?.coerce ?? false,
        ...processCreateParams(params)
      });
    };
    ZodBoolean = class extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = Boolean(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.boolean) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.boolean,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodBoolean.create = (params) => {
      return new ZodBoolean({
        typeName: ZodFirstPartyTypeKind.ZodBoolean,
        coerce: params?.coerce || false,
        ...processCreateParams(params)
      });
    };
    ZodDate = class _ZodDate extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = new Date(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.date) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.date,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        if (Number.isNaN(input.data.getTime())) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_date
          });
          return INVALID;
        }
        const status = new ParseStatus();
        let ctx = void 0;
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            if (input.data.getTime() < check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                message: check.message,
                inclusive: true,
                exact: false,
                minimum: check.value,
                type: "date"
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            if (input.data.getTime() > check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                message: check.message,
                inclusive: true,
                exact: false,
                maximum: check.value,
                type: "date"
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        return {
          status: status.value,
          value: new Date(input.data.getTime())
        };
      }
      _addCheck(check) {
        return new _ZodDate({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      min(minDate, message) {
        return this._addCheck({
          kind: "min",
          value: minDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      max(maxDate, message) {
        return this._addCheck({
          kind: "max",
          value: maxDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      get minDate() {
        let min2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min2 === null || ch.value > min2)
              min2 = ch.value;
          }
        }
        return min2 != null ? new Date(min2) : null;
      }
      get maxDate() {
        let max2 = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max2 === null || ch.value < max2)
              max2 = ch.value;
          }
        }
        return max2 != null ? new Date(max2) : null;
      }
    };
    ZodDate.create = (params) => {
      return new ZodDate({
        checks: [],
        coerce: params?.coerce || false,
        typeName: ZodFirstPartyTypeKind.ZodDate,
        ...processCreateParams(params)
      });
    };
    ZodSymbol = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.symbol) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.symbol,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodSymbol.create = (params) => {
      return new ZodSymbol({
        typeName: ZodFirstPartyTypeKind.ZodSymbol,
        ...processCreateParams(params)
      });
    };
    ZodUndefined = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.undefined,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodUndefined.create = (params) => {
      return new ZodUndefined({
        typeName: ZodFirstPartyTypeKind.ZodUndefined,
        ...processCreateParams(params)
      });
    };
    ZodNull = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.null) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.null,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodNull.create = (params) => {
      return new ZodNull({
        typeName: ZodFirstPartyTypeKind.ZodNull,
        ...processCreateParams(params)
      });
    };
    ZodAny = class extends ZodType {
      constructor() {
        super(...arguments);
        this._any = true;
      }
      _parse(input) {
        return OK(input.data);
      }
    };
    ZodAny.create = (params) => {
      return new ZodAny({
        typeName: ZodFirstPartyTypeKind.ZodAny,
        ...processCreateParams(params)
      });
    };
    ZodUnknown = class extends ZodType {
      constructor() {
        super(...arguments);
        this._unknown = true;
      }
      _parse(input) {
        return OK(input.data);
      }
    };
    ZodUnknown.create = (params) => {
      return new ZodUnknown({
        typeName: ZodFirstPartyTypeKind.ZodUnknown,
        ...processCreateParams(params)
      });
    };
    ZodNever = class extends ZodType {
      _parse(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_type,
          expected: ZodParsedType.never,
          received: ctx.parsedType
        });
        return INVALID;
      }
    };
    ZodNever.create = (params) => {
      return new ZodNever({
        typeName: ZodFirstPartyTypeKind.ZodNever,
        ...processCreateParams(params)
      });
    };
    ZodVoid = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.void,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodVoid.create = (params) => {
      return new ZodVoid({
        typeName: ZodFirstPartyTypeKind.ZodVoid,
        ...processCreateParams(params)
      });
    };
    ZodArray = class _ZodArray extends ZodType {
      _parse(input) {
        const { ctx, status } = this._processInputParams(input);
        const def = this._def;
        if (ctx.parsedType !== ZodParsedType.array) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.array,
            received: ctx.parsedType
          });
          return INVALID;
        }
        if (def.exactLength !== null) {
          const tooBig = ctx.data.length > def.exactLength.value;
          const tooSmall = ctx.data.length < def.exactLength.value;
          if (tooBig || tooSmall) {
            addIssueToContext(ctx, {
              code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
              minimum: tooSmall ? def.exactLength.value : void 0,
              maximum: tooBig ? def.exactLength.value : void 0,
              type: "array",
              inclusive: true,
              exact: true,
              message: def.exactLength.message
            });
            status.dirty();
          }
        }
        if (def.minLength !== null) {
          if (ctx.data.length < def.minLength.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: def.minLength.value,
              type: "array",
              inclusive: true,
              exact: false,
              message: def.minLength.message
            });
            status.dirty();
          }
        }
        if (def.maxLength !== null) {
          if (ctx.data.length > def.maxLength.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: def.maxLength.value,
              type: "array",
              inclusive: true,
              exact: false,
              message: def.maxLength.message
            });
            status.dirty();
          }
        }
        if (ctx.common.async) {
          return Promise.all([...ctx.data].map((item, i) => {
            return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
          })).then((result2) => {
            return ParseStatus.mergeArray(status, result2);
          });
        }
        const result = [...ctx.data].map((item, i) => {
          return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
        });
        return ParseStatus.mergeArray(status, result);
      }
      get element() {
        return this._def.type;
      }
      min(minLength, message) {
        return new _ZodArray({
          ...this._def,
          minLength: { value: minLength, message: errorUtil.toString(message) }
        });
      }
      max(maxLength, message) {
        return new _ZodArray({
          ...this._def,
          maxLength: { value: maxLength, message: errorUtil.toString(message) }
        });
      }
      length(len, message) {
        return new _ZodArray({
          ...this._def,
          exactLength: { value: len, message: errorUtil.toString(message) }
        });
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    ZodArray.create = (schema5, params) => {
      return new ZodArray({
        type: schema5,
        minLength: null,
        maxLength: null,
        exactLength: null,
        typeName: ZodFirstPartyTypeKind.ZodArray,
        ...processCreateParams(params)
      });
    };
    ZodObject = class _ZodObject extends ZodType {
      constructor() {
        super(...arguments);
        this._cached = null;
        this.nonstrict = this.passthrough;
        this.augment = this.extend;
      }
      _getCached() {
        if (this._cached !== null)
          return this._cached;
        const shape = this._def.shape();
        const keys = util.objectKeys(shape);
        this._cached = { shape, keys };
        return this._cached;
      }
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.object) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        const { status, ctx } = this._processInputParams(input);
        const { shape, keys: shapeKeys } = this._getCached();
        const extraKeys = [];
        if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
          for (const key in ctx.data) {
            if (!shapeKeys.includes(key)) {
              extraKeys.push(key);
            }
          }
        }
        const pairs = [];
        for (const key of shapeKeys) {
          const keyValidator = shape[key];
          const value = ctx.data[key];
          pairs.push({
            key: { status: "valid", value: key },
            value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (this._def.catchall instanceof ZodNever) {
          const unknownKeys = this._def.unknownKeys;
          if (unknownKeys === "passthrough") {
            for (const key of extraKeys) {
              pairs.push({
                key: { status: "valid", value: key },
                value: { status: "valid", value: ctx.data[key] }
              });
            }
          } else if (unknownKeys === "strict") {
            if (extraKeys.length > 0) {
              addIssueToContext(ctx, {
                code: ZodIssueCode.unrecognized_keys,
                keys: extraKeys
              });
              status.dirty();
            }
          } else if (unknownKeys === "strip") {
          } else {
            throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
          }
        } else {
          const catchall = this._def.catchall;
          for (const key of extraKeys) {
            const value = ctx.data[key];
            pairs.push({
              key: { status: "valid", value: key },
              value: catchall._parse(
                new ParseInputLazyPath(ctx, value, ctx.path, key)
                //, ctx.child(key), value, getParsedType(value)
              ),
              alwaysSet: key in ctx.data
            });
          }
        }
        if (ctx.common.async) {
          return Promise.resolve().then(async () => {
            const syncPairs = [];
            for (const pair of pairs) {
              const key = await pair.key;
              const value = await pair.value;
              syncPairs.push({
                key,
                value,
                alwaysSet: pair.alwaysSet
              });
            }
            return syncPairs;
          }).then((syncPairs) => {
            return ParseStatus.mergeObjectSync(status, syncPairs);
          });
        } else {
          return ParseStatus.mergeObjectSync(status, pairs);
        }
      }
      get shape() {
        return this._def.shape();
      }
      strict(message) {
        errorUtil.errToObj;
        return new _ZodObject({
          ...this._def,
          unknownKeys: "strict",
          ...message !== void 0 ? {
            errorMap: (issue, ctx) => {
              const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
              if (issue.code === "unrecognized_keys")
                return {
                  message: errorUtil.errToObj(message).message ?? defaultError
                };
              return {
                message: defaultError
              };
            }
          } : {}
        });
      }
      strip() {
        return new _ZodObject({
          ...this._def,
          unknownKeys: "strip"
        });
      }
      passthrough() {
        return new _ZodObject({
          ...this._def,
          unknownKeys: "passthrough"
        });
      }
      // const AugmentFactory =
      //   <Def extends ZodObjectDef>(def: Def) =>
      //   <Augmentation extends ZodRawShape>(
      //     augmentation: Augmentation
      //   ): ZodObject<
      //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
      //     Def["unknownKeys"],
      //     Def["catchall"]
      //   > => {
      //     return new ZodObject({
      //       ...def,
      //       shape: () => ({
      //         ...def.shape(),
      //         ...augmentation,
      //       }),
      //     }) as any;
      //   };
      extend(augmentation) {
        return new _ZodObject({
          ...this._def,
          shape: () => ({
            ...this._def.shape(),
            ...augmentation
          })
        });
      }
      /**
       * Prior to zod@1.0.12 there was a bug in the
       * inferred type of merged objects. Please
       * upgrade if you are experiencing issues.
       */
      merge(merging) {
        const merged = new _ZodObject({
          unknownKeys: merging._def.unknownKeys,
          catchall: merging._def.catchall,
          shape: () => ({
            ...this._def.shape(),
            ...merging._def.shape()
          }),
          typeName: ZodFirstPartyTypeKind.ZodObject
        });
        return merged;
      }
      // merge<
      //   Incoming extends AnyZodObject,
      //   Augmentation extends Incoming["shape"],
      //   NewOutput extends {
      //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
      //       ? Augmentation[k]["_output"]
      //       : k extends keyof Output
      //       ? Output[k]
      //       : never;
      //   },
      //   NewInput extends {
      //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
      //       ? Augmentation[k]["_input"]
      //       : k extends keyof Input
      //       ? Input[k]
      //       : never;
      //   }
      // >(
      //   merging: Incoming
      // ): ZodObject<
      //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
      //   Incoming["_def"]["unknownKeys"],
      //   Incoming["_def"]["catchall"],
      //   NewOutput,
      //   NewInput
      // > {
      //   const merged: any = new ZodObject({
      //     unknownKeys: merging._def.unknownKeys,
      //     catchall: merging._def.catchall,
      //     shape: () =>
      //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
      //     typeName: ZodFirstPartyTypeKind.ZodObject,
      //   }) as any;
      //   return merged;
      // }
      setKey(key, schema5) {
        return this.augment({ [key]: schema5 });
      }
      // merge<Incoming extends AnyZodObject>(
      //   merging: Incoming
      // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
      // ZodObject<
      //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
      //   Incoming["_def"]["unknownKeys"],
      //   Incoming["_def"]["catchall"]
      // > {
      //   // const mergedShape = objectUtil.mergeShapes(
      //   //   this._def.shape(),
      //   //   merging._def.shape()
      //   // );
      //   const merged: any = new ZodObject({
      //     unknownKeys: merging._def.unknownKeys,
      //     catchall: merging._def.catchall,
      //     shape: () =>
      //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
      //     typeName: ZodFirstPartyTypeKind.ZodObject,
      //   }) as any;
      //   return merged;
      // }
      catchall(index6) {
        return new _ZodObject({
          ...this._def,
          catchall: index6
        });
      }
      pick(mask) {
        const shape = {};
        for (const key of util.objectKeys(mask)) {
          if (mask[key] && this.shape[key]) {
            shape[key] = this.shape[key];
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      omit(mask) {
        const shape = {};
        for (const key of util.objectKeys(this.shape)) {
          if (!mask[key]) {
            shape[key] = this.shape[key];
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      /**
       * @deprecated
       */
      deepPartial() {
        return deepPartialify(this);
      }
      partial(mask) {
        const newShape = {};
        for (const key of util.objectKeys(this.shape)) {
          const fieldSchema = this.shape[key];
          if (mask && !mask[key]) {
            newShape[key] = fieldSchema;
          } else {
            newShape[key] = fieldSchema.optional();
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => newShape
        });
      }
      required(mask) {
        const newShape = {};
        for (const key of util.objectKeys(this.shape)) {
          if (mask && !mask[key]) {
            newShape[key] = this.shape[key];
          } else {
            const fieldSchema = this.shape[key];
            let newField = fieldSchema;
            while (newField instanceof ZodOptional) {
              newField = newField._def.innerType;
            }
            newShape[key] = newField;
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => newShape
        });
      }
      keyof() {
        return createZodEnum(util.objectKeys(this.shape));
      }
    };
    ZodObject.create = (shape, params) => {
      return new ZodObject({
        shape: () => shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodObject.strictCreate = (shape, params) => {
      return new ZodObject({
        shape: () => shape,
        unknownKeys: "strict",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodObject.lazycreate = (shape, params) => {
      return new ZodObject({
        shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodUnion = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const options = this._def.options;
        function handleResults(results) {
          for (const result of results) {
            if (result.result.status === "valid") {
              return result.result;
            }
          }
          for (const result of results) {
            if (result.result.status === "dirty") {
              ctx.common.issues.push(...result.ctx.common.issues);
              return result.result;
            }
          }
          const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union,
            unionErrors
          });
          return INVALID;
        }
        if (ctx.common.async) {
          return Promise.all(options.map(async (option) => {
            const childCtx = {
              ...ctx,
              common: {
                ...ctx.common,
                issues: []
              },
              parent: null
            };
            return {
              result: await option._parseAsync({
                data: ctx.data,
                path: ctx.path,
                parent: childCtx
              }),
              ctx: childCtx
            };
          })).then(handleResults);
        } else {
          let dirty = void 0;
          const issues = [];
          for (const option of options) {
            const childCtx = {
              ...ctx,
              common: {
                ...ctx.common,
                issues: []
              },
              parent: null
            };
            const result = option._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: childCtx
            });
            if (result.status === "valid") {
              return result;
            } else if (result.status === "dirty" && !dirty) {
              dirty = { result, ctx: childCtx };
            }
            if (childCtx.common.issues.length) {
              issues.push(childCtx.common.issues);
            }
          }
          if (dirty) {
            ctx.common.issues.push(...dirty.ctx.common.issues);
            return dirty.result;
          }
          const unionErrors = issues.map((issues2) => new ZodError(issues2));
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union,
            unionErrors
          });
          return INVALID;
        }
      }
      get options() {
        return this._def.options;
      }
    };
    ZodUnion.create = (types, params) => {
      return new ZodUnion({
        options: types,
        typeName: ZodFirstPartyTypeKind.ZodUnion,
        ...processCreateParams(params)
      });
    };
    getDiscriminator = (type) => {
      if (type instanceof ZodLazy) {
        return getDiscriminator(type.schema);
      } else if (type instanceof ZodEffects) {
        return getDiscriminator(type.innerType());
      } else if (type instanceof ZodLiteral) {
        return [type.value];
      } else if (type instanceof ZodEnum) {
        return type.options;
      } else if (type instanceof ZodNativeEnum) {
        return util.objectValues(type.enum);
      } else if (type instanceof ZodDefault) {
        return getDiscriminator(type._def.innerType);
      } else if (type instanceof ZodUndefined) {
        return [void 0];
      } else if (type instanceof ZodNull) {
        return [null];
      } else if (type instanceof ZodOptional) {
        return [void 0, ...getDiscriminator(type.unwrap())];
      } else if (type instanceof ZodNullable) {
        return [null, ...getDiscriminator(type.unwrap())];
      } else if (type instanceof ZodBranded) {
        return getDiscriminator(type.unwrap());
      } else if (type instanceof ZodReadonly) {
        return getDiscriminator(type.unwrap());
      } else if (type instanceof ZodCatch) {
        return getDiscriminator(type._def.innerType);
      } else {
        return [];
      }
    };
    ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const discriminator = this.discriminator;
        const discriminatorValue = ctx.data[discriminator];
        const option = this.optionsMap.get(discriminatorValue);
        if (!option) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union_discriminator,
            options: Array.from(this.optionsMap.keys()),
            path: [discriminator]
          });
          return INVALID;
        }
        if (ctx.common.async) {
          return option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
        } else {
          return option._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
        }
      }
      get discriminator() {
        return this._def.discriminator;
      }
      get options() {
        return this._def.options;
      }
      get optionsMap() {
        return this._def.optionsMap;
      }
      /**
       * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
       * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
       * have a different value for each object in the union.
       * @param discriminator the name of the discriminator property
       * @param types an array of object schemas
       * @param params
       */
      static create(discriminator, options, params) {
        const optionsMap = /* @__PURE__ */ new Map();
        for (const type of options) {
          const discriminatorValues = getDiscriminator(type.shape[discriminator]);
          if (!discriminatorValues.length) {
            throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
          }
          for (const value of discriminatorValues) {
            if (optionsMap.has(value)) {
              throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
            }
            optionsMap.set(value, type);
          }
        }
        return new _ZodDiscriminatedUnion({
          typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
          discriminator,
          options,
          optionsMap,
          ...processCreateParams(params)
        });
      }
    };
    ZodIntersection = class extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const handleParsed = (parsedLeft, parsedRight) => {
          if (isAborted(parsedLeft) || isAborted(parsedRight)) {
            return INVALID;
          }
          const merged = mergeValues(parsedLeft.value, parsedRight.value);
          if (!merged.valid) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.invalid_intersection_types
            });
            return INVALID;
          }
          if (isDirty(parsedLeft) || isDirty(parsedRight)) {
            status.dirty();
          }
          return { status: status.value, value: merged.data };
        };
        if (ctx.common.async) {
          return Promise.all([
            this._def.left._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            }),
            this._def.right._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            })
          ]).then(([left, right]) => handleParsed(left, right));
        } else {
          return handleParsed(this._def.left._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          }), this._def.right._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          }));
        }
      }
    };
    ZodIntersection.create = (left, right, params) => {
      return new ZodIntersection({
        left,
        right,
        typeName: ZodFirstPartyTypeKind.ZodIntersection,
        ...processCreateParams(params)
      });
    };
    ZodTuple = class _ZodTuple extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.array) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.array,
            received: ctx.parsedType
          });
          return INVALID;
        }
        if (ctx.data.length < this._def.items.length) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: this._def.items.length,
            inclusive: true,
            exact: false,
            type: "array"
          });
          return INVALID;
        }
        const rest = this._def.rest;
        if (!rest && ctx.data.length > this._def.items.length) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: this._def.items.length,
            inclusive: true,
            exact: false,
            type: "array"
          });
          status.dirty();
        }
        const items = [...ctx.data].map((item, itemIndex) => {
          const schema5 = this._def.items[itemIndex] || this._def.rest;
          if (!schema5)
            return null;
          return schema5._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
        }).filter((x) => !!x);
        if (ctx.common.async) {
          return Promise.all(items).then((results) => {
            return ParseStatus.mergeArray(status, results);
          });
        } else {
          return ParseStatus.mergeArray(status, items);
        }
      }
      get items() {
        return this._def.items;
      }
      rest(rest) {
        return new _ZodTuple({
          ...this._def,
          rest
        });
      }
    };
    ZodTuple.create = (schemas, params) => {
      if (!Array.isArray(schemas)) {
        throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
      }
      return new ZodTuple({
        items: schemas,
        typeName: ZodFirstPartyTypeKind.ZodTuple,
        rest: null,
        ...processCreateParams(params)
      });
    };
    ZodRecord = class _ZodRecord extends ZodType {
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const pairs = [];
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        for (const key in ctx.data) {
          pairs.push({
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
            value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (ctx.common.async) {
          return ParseStatus.mergeObjectAsync(status, pairs);
        } else {
          return ParseStatus.mergeObjectSync(status, pairs);
        }
      }
      get element() {
        return this._def.valueType;
      }
      static create(first, second, third) {
        if (second instanceof ZodType) {
          return new _ZodRecord({
            keyType: first,
            valueType: second,
            typeName: ZodFirstPartyTypeKind.ZodRecord,
            ...processCreateParams(third)
          });
        }
        return new _ZodRecord({
          keyType: ZodString.create(),
          valueType: first,
          typeName: ZodFirstPartyTypeKind.ZodRecord,
          ...processCreateParams(second)
        });
      }
    };
    ZodMap = class extends ZodType {
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.map) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.map,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        const pairs = [...ctx.data.entries()].map(([key, value], index6) => {
          return {
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index6, "key"])),
            value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index6, "value"]))
          };
        });
        if (ctx.common.async) {
          const finalMap = /* @__PURE__ */ new Map();
          return Promise.resolve().then(async () => {
            for (const pair of pairs) {
              const key = await pair.key;
              const value = await pair.value;
              if (key.status === "aborted" || value.status === "aborted") {
                return INVALID;
              }
              if (key.status === "dirty" || value.status === "dirty") {
                status.dirty();
              }
              finalMap.set(key.value, value.value);
            }
            return { status: status.value, value: finalMap };
          });
        } else {
          const finalMap = /* @__PURE__ */ new Map();
          for (const pair of pairs) {
            const key = pair.key;
            const value = pair.value;
            if (key.status === "aborted" || value.status === "aborted") {
              return INVALID;
            }
            if (key.status === "dirty" || value.status === "dirty") {
              status.dirty();
            }
            finalMap.set(key.value, value.value);
          }
          return { status: status.value, value: finalMap };
        }
      }
    };
    ZodMap.create = (keyType, valueType, params) => {
      return new ZodMap({
        valueType,
        keyType,
        typeName: ZodFirstPartyTypeKind.ZodMap,
        ...processCreateParams(params)
      });
    };
    ZodSet = class _ZodSet extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.set) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.set,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const def = this._def;
        if (def.minSize !== null) {
          if (ctx.data.size < def.minSize.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: def.minSize.value,
              type: "set",
              inclusive: true,
              exact: false,
              message: def.minSize.message
            });
            status.dirty();
          }
        }
        if (def.maxSize !== null) {
          if (ctx.data.size > def.maxSize.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: def.maxSize.value,
              type: "set",
              inclusive: true,
              exact: false,
              message: def.maxSize.message
            });
            status.dirty();
          }
        }
        const valueType = this._def.valueType;
        function finalizeSet(elements2) {
          const parsedSet = /* @__PURE__ */ new Set();
          for (const element of elements2) {
            if (element.status === "aborted")
              return INVALID;
            if (element.status === "dirty")
              status.dirty();
            parsedSet.add(element.value);
          }
          return { status: status.value, value: parsedSet };
        }
        const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
        if (ctx.common.async) {
          return Promise.all(elements).then((elements2) => finalizeSet(elements2));
        } else {
          return finalizeSet(elements);
        }
      }
      min(minSize, message) {
        return new _ZodSet({
          ...this._def,
          minSize: { value: minSize, message: errorUtil.toString(message) }
        });
      }
      max(maxSize, message) {
        return new _ZodSet({
          ...this._def,
          maxSize: { value: maxSize, message: errorUtil.toString(message) }
        });
      }
      size(size, message) {
        return this.min(size, message).max(size, message);
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    ZodSet.create = (valueType, params) => {
      return new ZodSet({
        valueType,
        minSize: null,
        maxSize: null,
        typeName: ZodFirstPartyTypeKind.ZodSet,
        ...processCreateParams(params)
      });
    };
    ZodFunction = class _ZodFunction extends ZodType {
      constructor() {
        super(...arguments);
        this.validate = this.implement;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.function) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.function,
            received: ctx.parsedType
          });
          return INVALID;
        }
        function makeArgsIssue(args, error2) {
          return makeIssue({
            data: args,
            path: ctx.path,
            errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
            issueData: {
              code: ZodIssueCode.invalid_arguments,
              argumentsError: error2
            }
          });
        }
        function makeReturnsIssue(returns, error2) {
          return makeIssue({
            data: returns,
            path: ctx.path,
            errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
            issueData: {
              code: ZodIssueCode.invalid_return_type,
              returnTypeError: error2
            }
          });
        }
        const params = { errorMap: ctx.common.contextualErrorMap };
        const fn = ctx.data;
        if (this._def.returns instanceof ZodPromise) {
          const me = this;
          return OK(async function(...args) {
            const error2 = new ZodError([]);
            const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
              error2.addIssue(makeArgsIssue(args, e));
              throw error2;
            });
            const result = await Reflect.apply(fn, this, parsedArgs);
            const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
              error2.addIssue(makeReturnsIssue(result, e));
              throw error2;
            });
            return parsedReturns;
          });
        } else {
          const me = this;
          return OK(function(...args) {
            const parsedArgs = me._def.args.safeParse(args, params);
            if (!parsedArgs.success) {
              throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
            }
            const result = Reflect.apply(fn, this, parsedArgs.data);
            const parsedReturns = me._def.returns.safeParse(result, params);
            if (!parsedReturns.success) {
              throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
            }
            return parsedReturns.data;
          });
        }
      }
      parameters() {
        return this._def.args;
      }
      returnType() {
        return this._def.returns;
      }
      args(...items) {
        return new _ZodFunction({
          ...this._def,
          args: ZodTuple.create(items).rest(ZodUnknown.create())
        });
      }
      returns(returnType) {
        return new _ZodFunction({
          ...this._def,
          returns: returnType
        });
      }
      implement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
      }
      strictImplement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
      }
      static create(args, returns, params) {
        return new _ZodFunction({
          args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
          returns: returns || ZodUnknown.create(),
          typeName: ZodFirstPartyTypeKind.ZodFunction,
          ...processCreateParams(params)
        });
      }
    };
    ZodLazy = class extends ZodType {
      get schema() {
        return this._def.getter();
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const lazySchema = this._def.getter();
        return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
      }
    };
    ZodLazy.create = (getter, params) => {
      return new ZodLazy({
        getter,
        typeName: ZodFirstPartyTypeKind.ZodLazy,
        ...processCreateParams(params)
      });
    };
    ZodLiteral = class extends ZodType {
      _parse(input) {
        if (input.data !== this._def.value) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_literal,
            expected: this._def.value
          });
          return INVALID;
        }
        return { status: "valid", value: input.data };
      }
      get value() {
        return this._def.value;
      }
    };
    ZodLiteral.create = (value, params) => {
      return new ZodLiteral({
        value,
        typeName: ZodFirstPartyTypeKind.ZodLiteral,
        ...processCreateParams(params)
      });
    };
    ZodEnum = class _ZodEnum extends ZodType {
      _parse(input) {
        if (typeof input.data !== "string") {
          const ctx = this._getOrReturnCtx(input);
          const expectedValues = this._def.values;
          addIssueToContext(ctx, {
            expected: util.joinValues(expectedValues),
            received: ctx.parsedType,
            code: ZodIssueCode.invalid_type
          });
          return INVALID;
        }
        if (!this._cache) {
          this._cache = new Set(this._def.values);
        }
        if (!this._cache.has(input.data)) {
          const ctx = this._getOrReturnCtx(input);
          const expectedValues = this._def.values;
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return INVALID;
        }
        return OK(input.data);
      }
      get options() {
        return this._def.values;
      }
      get enum() {
        const enumValues = {};
        for (const val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      get Values() {
        const enumValues = {};
        for (const val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      get Enum() {
        const enumValues = {};
        for (const val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      extract(values, newDef = this._def) {
        return _ZodEnum.create(values, {
          ...this._def,
          ...newDef
        });
      }
      exclude(values, newDef = this._def) {
        return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
          ...this._def,
          ...newDef
        });
      }
    };
    ZodEnum.create = createZodEnum;
    ZodNativeEnum = class extends ZodType {
      _parse(input) {
        const nativeEnumValues = util.getValidEnumValues(this._def.values);
        const ctx = this._getOrReturnCtx(input);
        if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
          const expectedValues = util.objectValues(nativeEnumValues);
          addIssueToContext(ctx, {
            expected: util.joinValues(expectedValues),
            received: ctx.parsedType,
            code: ZodIssueCode.invalid_type
          });
          return INVALID;
        }
        if (!this._cache) {
          this._cache = new Set(util.getValidEnumValues(this._def.values));
        }
        if (!this._cache.has(input.data)) {
          const expectedValues = util.objectValues(nativeEnumValues);
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return INVALID;
        }
        return OK(input.data);
      }
      get enum() {
        return this._def.values;
      }
    };
    ZodNativeEnum.create = (values, params) => {
      return new ZodNativeEnum({
        values,
        typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
        ...processCreateParams(params)
      });
    };
    ZodPromise = class extends ZodType {
      unwrap() {
        return this._def.type;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.promise,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
        return OK(promisified.then((data) => {
          return this._def.type.parseAsync(data, {
            path: ctx.path,
            errorMap: ctx.common.contextualErrorMap
          });
        }));
      }
    };
    ZodPromise.create = (schema5, params) => {
      return new ZodPromise({
        type: schema5,
        typeName: ZodFirstPartyTypeKind.ZodPromise,
        ...processCreateParams(params)
      });
    };
    ZodEffects = class extends ZodType {
      innerType() {
        return this._def.schema;
      }
      sourceType() {
        return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const effect = this._def.effect || null;
        const checkCtx = {
          addIssue: (arg) => {
            addIssueToContext(ctx, arg);
            if (arg.fatal) {
              status.abort();
            } else {
              status.dirty();
            }
          },
          get path() {
            return ctx.path;
          }
        };
        checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
        if (effect.type === "preprocess") {
          const processed = effect.transform(ctx.data, checkCtx);
          if (ctx.common.async) {
            return Promise.resolve(processed).then(async (processed2) => {
              if (status.value === "aborted")
                return INVALID;
              const result = await this._def.schema._parseAsync({
                data: processed2,
                path: ctx.path,
                parent: ctx
              });
              if (result.status === "aborted")
                return INVALID;
              if (result.status === "dirty")
                return DIRTY(result.value);
              if (status.value === "dirty")
                return DIRTY(result.value);
              return result;
            });
          } else {
            if (status.value === "aborted")
              return INVALID;
            const result = this._def.schema._parseSync({
              data: processed,
              path: ctx.path,
              parent: ctx
            });
            if (result.status === "aborted")
              return INVALID;
            if (result.status === "dirty")
              return DIRTY(result.value);
            if (status.value === "dirty")
              return DIRTY(result.value);
            return result;
          }
        }
        if (effect.type === "refinement") {
          const executeRefinement = (acc) => {
            const result = effect.refinement(acc, checkCtx);
            if (ctx.common.async) {
              return Promise.resolve(result);
            }
            if (result instanceof Promise) {
              throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
            }
            return acc;
          };
          if (ctx.common.async === false) {
            const inner = this._def.schema._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (inner.status === "aborted")
              return INVALID;
            if (inner.status === "dirty")
              status.dirty();
            executeRefinement(inner.value);
            return { status: status.value, value: inner.value };
          } else {
            return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
              if (inner.status === "aborted")
                return INVALID;
              if (inner.status === "dirty")
                status.dirty();
              return executeRefinement(inner.value).then(() => {
                return { status: status.value, value: inner.value };
              });
            });
          }
        }
        if (effect.type === "transform") {
          if (ctx.common.async === false) {
            const base = this._def.schema._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (!isValid(base))
              return INVALID;
            const result = effect.transform(base.value, checkCtx);
            if (result instanceof Promise) {
              throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
            }
            return { status: status.value, value: result };
          } else {
            return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
              if (!isValid(base))
                return INVALID;
              return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
                status: status.value,
                value: result
              }));
            });
          }
        }
        util.assertNever(effect);
      }
    };
    ZodEffects.create = (schema5, effect, params) => {
      return new ZodEffects({
        schema: schema5,
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        effect,
        ...processCreateParams(params)
      });
    };
    ZodEffects.createWithPreprocess = (preprocess, schema5, params) => {
      return new ZodEffects({
        schema: schema5,
        effect: { type: "preprocess", transform: preprocess },
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        ...processCreateParams(params)
      });
    };
    ZodOptional = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.undefined) {
          return OK(void 0);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodOptional.create = (type, params) => {
      return new ZodOptional({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodOptional,
        ...processCreateParams(params)
      });
    };
    ZodNullable = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.null) {
          return OK(null);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodNullable.create = (type, params) => {
      return new ZodNullable({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodNullable,
        ...processCreateParams(params)
      });
    };
    ZodDefault = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        let data = ctx.data;
        if (ctx.parsedType === ZodParsedType.undefined) {
          data = this._def.defaultValue();
        }
        return this._def.innerType._parse({
          data,
          path: ctx.path,
          parent: ctx
        });
      }
      removeDefault() {
        return this._def.innerType;
      }
    };
    ZodDefault.create = (type, params) => {
      return new ZodDefault({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodDefault,
        defaultValue: typeof params.default === "function" ? params.default : () => params.default,
        ...processCreateParams(params)
      });
    };
    ZodCatch = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const newCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          }
        };
        const result = this._def.innerType._parse({
          data: newCtx.data,
          path: newCtx.path,
          parent: {
            ...newCtx
          }
        });
        if (isAsync(result)) {
          return result.then((result2) => {
            return {
              status: "valid",
              value: result2.status === "valid" ? result2.value : this._def.catchValue({
                get error() {
                  return new ZodError(newCtx.common.issues);
                },
                input: newCtx.data
              })
            };
          });
        } else {
          return {
            status: "valid",
            value: result.status === "valid" ? result.value : this._def.catchValue({
              get error() {
                return new ZodError(newCtx.common.issues);
              },
              input: newCtx.data
            })
          };
        }
      }
      removeCatch() {
        return this._def.innerType;
      }
    };
    ZodCatch.create = (type, params) => {
      return new ZodCatch({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodCatch,
        catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
        ...processCreateParams(params)
      });
    };
    ZodNaN = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.nan) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.nan,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return { status: "valid", value: input.data };
      }
    };
    ZodNaN.create = (params) => {
      return new ZodNaN({
        typeName: ZodFirstPartyTypeKind.ZodNaN,
        ...processCreateParams(params)
      });
    };
    BRAND = Symbol("zod_brand");
    ZodBranded = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const data = ctx.data;
        return this._def.type._parse({
          data,
          path: ctx.path,
          parent: ctx
        });
      }
      unwrap() {
        return this._def.type;
      }
    };
    ZodPipeline = class _ZodPipeline extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.common.async) {
          const handleAsync = async () => {
            const inResult = await this._def.in._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (inResult.status === "aborted")
              return INVALID;
            if (inResult.status === "dirty") {
              status.dirty();
              return DIRTY(inResult.value);
            } else {
              return this._def.out._parseAsync({
                data: inResult.value,
                path: ctx.path,
                parent: ctx
              });
            }
          };
          return handleAsync();
        } else {
          const inResult = this._def.in._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
          if (inResult.status === "aborted")
            return INVALID;
          if (inResult.status === "dirty") {
            status.dirty();
            return {
              status: "dirty",
              value: inResult.value
            };
          } else {
            return this._def.out._parseSync({
              data: inResult.value,
              path: ctx.path,
              parent: ctx
            });
          }
        }
      }
      static create(a, b) {
        return new _ZodPipeline({
          in: a,
          out: b,
          typeName: ZodFirstPartyTypeKind.ZodPipeline
        });
      }
    };
    ZodReadonly = class extends ZodType {
      _parse(input) {
        const result = this._def.innerType._parse(input);
        const freeze = (data) => {
          if (isValid(data)) {
            data.value = Object.freeze(data.value);
          }
          return data;
        };
        return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodReadonly.create = (type, params) => {
      return new ZodReadonly({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodReadonly,
        ...processCreateParams(params)
      });
    };
    late = {
      object: ZodObject.lazycreate
    };
    (function(ZodFirstPartyTypeKind2) {
      ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
      ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
      ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
      ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
      ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
      ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
      ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
      ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
      ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
      ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
      ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
      ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
      ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
      ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
      ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
      ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
      ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
      ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
      ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
      ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
      ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
      ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
      ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
      ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
      ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
      ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
      ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
      ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
      ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
      ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
      ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
      ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
      ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
      ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
      ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
      ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
    })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
    stringType = ZodString.create;
    numberType = ZodNumber.create;
    nanType = ZodNaN.create;
    bigIntType = ZodBigInt.create;
    booleanType = ZodBoolean.create;
    dateType = ZodDate.create;
    symbolType = ZodSymbol.create;
    undefinedType = ZodUndefined.create;
    nullType = ZodNull.create;
    anyType = ZodAny.create;
    unknownType = ZodUnknown.create;
    neverType = ZodNever.create;
    voidType = ZodVoid.create;
    arrayType = ZodArray.create;
    objectType = ZodObject.create;
    strictObjectType = ZodObject.strictCreate;
    unionType = ZodUnion.create;
    discriminatedUnionType = ZodDiscriminatedUnion.create;
    intersectionType = ZodIntersection.create;
    tupleType = ZodTuple.create;
    recordType = ZodRecord.create;
    mapType = ZodMap.create;
    setType = ZodSet.create;
    functionType = ZodFunction.create;
    lazyType = ZodLazy.create;
    literalType = ZodLiteral.create;
    enumType = ZodEnum.create;
    nativeEnumType = ZodNativeEnum.create;
    promiseType = ZodPromise.create;
    effectsType = ZodEffects.create;
    optionalType = ZodOptional.create;
    nullableType = ZodNullable.create;
    preprocessType = ZodEffects.createWithPreprocess;
    pipelineType = ZodPipeline.create;
    coerce = {
      string: (arg) => ZodString.create({ ...arg, coerce: true }),
      number: (arg) => ZodNumber.create({ ...arg, coerce: true }),
      boolean: (arg) => ZodBoolean.create({
        ...arg,
        coerce: true
      }),
      bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }),
      date: (arg) => ZodDate.create({ ...arg, coerce: true })
    };
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/external.js
var init_external = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/external.js"() {
    "use strict";
    init_errors();
    init_parseUtil();
    init_typeAliases();
    init_util();
    init_types();
    init_ZodError();
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/index.js
var init_v3 = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/v3/index.js"() {
    "use strict";
    init_external();
    init_external();
  }
});

// ../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/index.js
var init_esm = __esm({
  "../node_modules/.pnpm/zod@3.25.42/node_modules/zod/dist/esm/index.js"() {
    "use strict";
    init_v3();
    init_v3();
  }
});

// src/serializer/gelSchema.ts
var enumSchema, enumSchemaV1, indexColumn, index, fk, sequenceSchema, roleSchema, sequenceSquashed, column, checkConstraint, columnSquashed, compositePK, uniqueConstraint, policy, policySquashed, viewWithOption, matViewWithOption, mergedViewWithOption, view, table, schemaHash, kitInternals, gelSchemaExternal, gelSchemaInternal, tableSquashed, gelSchemaSquashed, gelSchema, dryGel;
var init_gelSchema = __esm({
  "src/serializer/gelSchema.ts"() {
    "use strict";
    init_global();
    init_esm();
    enumSchema = objectType({
      name: stringType(),
      schema: stringType(),
      values: stringType().array()
    }).strict();
    enumSchemaV1 = objectType({
      name: stringType(),
      values: recordType(stringType(), stringType())
    }).strict();
    indexColumn = objectType({
      expression: stringType(),
      isExpression: booleanType(),
      asc: booleanType(),
      nulls: stringType().optional(),
      opclass: stringType().optional()
    });
    index = objectType({
      name: stringType(),
      columns: indexColumn.array(),
      isUnique: booleanType(),
      with: recordType(stringType(), anyType()).optional(),
      method: stringType().default("btree"),
      where: stringType().optional(),
      concurrently: booleanType().default(false)
    }).strict();
    fk = objectType({
      name: stringType(),
      tableFrom: stringType(),
      columnsFrom: stringType().array(),
      tableTo: stringType(),
      schemaTo: stringType().optional(),
      columnsTo: stringType().array(),
      onUpdate: stringType().optional(),
      onDelete: stringType().optional()
    }).strict();
    sequenceSchema = objectType({
      name: stringType(),
      increment: stringType().optional(),
      minValue: stringType().optional(),
      maxValue: stringType().optional(),
      startWith: stringType().optional(),
      cache: stringType().optional(),
      cycle: booleanType().optional(),
      schema: stringType()
    }).strict();
    roleSchema = objectType({
      name: stringType(),
      createDb: booleanType().optional(),
      createRole: booleanType().optional(),
      inherit: booleanType().optional()
    }).strict();
    sequenceSquashed = objectType({
      name: stringType(),
      schema: stringType(),
      values: stringType()
    }).strict();
    column = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional(),
      generated: objectType({
        type: literalType("stored"),
        as: stringType()
      }).optional(),
      identity: sequenceSchema.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional()
    }).strict();
    checkConstraint = objectType({
      name: stringType(),
      value: stringType()
    }).strict();
    columnSquashed = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional(),
      generated: objectType({
        type: literalType("stored"),
        as: stringType()
      }).optional(),
      identity: stringType().optional()
    }).strict();
    compositePK = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    uniqueConstraint = objectType({
      name: stringType(),
      columns: stringType().array(),
      nullsNotDistinct: booleanType()
    }).strict();
    policy = objectType({
      name: stringType(),
      as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
      for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
      to: stringType().array().optional(),
      using: stringType().optional(),
      withCheck: stringType().optional(),
      on: stringType().optional(),
      schema: stringType().optional()
    }).strict();
    policySquashed = objectType({
      name: stringType(),
      values: stringType()
    }).strict();
    viewWithOption = objectType({
      checkOption: enumType(["local", "cascaded"]).optional(),
      securityBarrier: booleanType().optional(),
      securityInvoker: booleanType().optional()
    }).strict();
    matViewWithOption = objectType({
      fillfactor: numberType().optional(),
      toastTupleTarget: numberType().optional(),
      parallelWorkers: numberType().optional(),
      autovacuumEnabled: booleanType().optional(),
      vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
      vacuumTruncate: booleanType().optional(),
      autovacuumVacuumThreshold: numberType().optional(),
      autovacuumVacuumScaleFactor: numberType().optional(),
      autovacuumVacuumCostDelay: numberType().optional(),
      autovacuumVacuumCostLimit: numberType().optional(),
      autovacuumFreezeMinAge: numberType().optional(),
      autovacuumFreezeMaxAge: numberType().optional(),
      autovacuumFreezeTableAge: numberType().optional(),
      autovacuumMultixactFreezeMinAge: numberType().optional(),
      autovacuumMultixactFreezeMaxAge: numberType().optional(),
      autovacuumMultixactFreezeTableAge: numberType().optional(),
      logAutovacuumMinDuration: numberType().optional(),
      userCatalogTable: booleanType().optional()
    }).strict();
    mergedViewWithOption = viewWithOption.merge(matViewWithOption).strict();
    view = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column),
      definition: stringType().optional(),
      materialized: booleanType(),
      with: mergedViewWithOption.optional(),
      isExisting: booleanType(),
      withNoData: booleanType().optional(),
      using: stringType().optional(),
      tablespace: stringType().optional()
    }).strict();
    table = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column),
      indexes: recordType(stringType(), index),
      foreignKeys: recordType(stringType(), fk),
      compositePrimaryKeys: recordType(stringType(), compositePK),
      uniqueConstraints: recordType(stringType(), uniqueConstraint).default({}),
      policies: recordType(stringType(), policy).default({}),
      checkConstraints: recordType(stringType(), checkConstraint).default({}),
      isRLSEnabled: booleanType().default(false)
    }).strict();
    schemaHash = objectType({
      id: stringType(),
      prevId: stringType()
    });
    kitInternals = objectType({
      tables: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({
              isArray: booleanType().optional(),
              dimensions: numberType().optional(),
              rawType: stringType().optional(),
              isDefaultAnExpression: booleanType().optional()
            }).optional()
          )
        }).optional()
      )
    }).optional();
    gelSchemaExternal = objectType({
      version: literalType("1"),
      dialect: literalType("gel"),
      tables: arrayType(table),
      enums: arrayType(enumSchemaV1),
      schemas: arrayType(objectType({ name: stringType() })),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      })
    }).strict();
    gelSchemaInternal = objectType({
      version: literalType("1"),
      dialect: literalType("gel"),
      tables: recordType(stringType(), table),
      enums: recordType(stringType(), enumSchema),
      schemas: recordType(stringType(), stringType()),
      views: recordType(stringType(), view).default({}),
      sequences: recordType(stringType(), sequenceSchema).default({}),
      roles: recordType(stringType(), roleSchema).default({}),
      policies: recordType(stringType(), policy).default({}),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals
    }).strict();
    tableSquashed = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), columnSquashed),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()),
      policies: recordType(stringType(), stringType()),
      checkConstraints: recordType(stringType(), stringType()),
      isRLSEnabled: booleanType().default(false)
    }).strict();
    gelSchemaSquashed = objectType({
      version: literalType("1"),
      dialect: literalType("gel"),
      tables: recordType(stringType(), tableSquashed),
      enums: recordType(stringType(), enumSchema),
      schemas: recordType(stringType(), stringType()),
      views: recordType(stringType(), view),
      sequences: recordType(stringType(), sequenceSquashed),
      roles: recordType(stringType(), roleSchema).default({}),
      policies: recordType(stringType(), policySquashed).default({})
    }).strict();
    gelSchema = gelSchemaInternal.merge(schemaHash);
    dryGel = gelSchema.parse({
      version: "1",
      dialect: "gel",
      id: originUUID,
      prevId: "",
      tables: {},
      enums: {},
      schemas: {},
      policies: {},
      roles: {},
      sequences: {},
      _meta: {
        schemas: {},
        tables: {},
        columns: {}
      }
    });
  }
});

// src/serializer/mysqlSchema.ts
var index2, fk2, column2, tableV3, compositePK2, uniqueConstraint2, checkConstraint2, tableV4, table2, viewMeta, view2, kitInternals2, dialect, schemaHash2, schemaInternalV3, schemaInternalV4, schemaInternalV5, schemaInternal, schemaV3, schemaV4, schemaV5, schema, tableSquashedV4, tableSquashed2, viewSquashed, schemaSquashed, schemaSquashedV4, MySqlSquasher, squashMysqlScheme, mysqlSchema, mysqlSchemaV5, mysqlSchemaSquashed, backwardCompatibleMysqlSchema, dryMySql;
var init_mysqlSchema = __esm({
  "src/serializer/mysqlSchema.ts"() {
    "use strict";
    init_esm();
    init_global();
    index2 = objectType({
      name: stringType(),
      columns: stringType().array(),
      isUnique: booleanType(),
      using: enumType(["btree", "hash"]).optional(),
      algorithm: enumType(["default", "inplace", "copy"]).optional(),
      lock: enumType(["default", "none", "shared", "exclusive"]).optional()
    }).strict();
    fk2 = objectType({
      name: stringType(),
      tableFrom: stringType(),
      columnsFrom: stringType().array(),
      tableTo: stringType(),
      columnsTo: stringType().array(),
      onUpdate: stringType().optional(),
      onDelete: stringType().optional()
    }).strict();
    column2 = objectType({
      name: stringType(),
      type: stringType(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      autoincrement: booleanType().optional(),
      default: anyType().optional(),
      onUpdate: anyType().optional(),
      generated: objectType({
        type: enumType(["stored", "virtual"]),
        as: stringType()
      }).optional()
    }).strict();
    tableV3 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), index2),
      foreignKeys: recordType(stringType(), fk2)
    }).strict();
    compositePK2 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    uniqueConstraint2 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    checkConstraint2 = objectType({
      name: stringType(),
      value: stringType()
    }).strict();
    tableV4 = objectType({
      name: stringType(),
      schema: stringType().optional(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), index2),
      foreignKeys: recordType(stringType(), fk2)
    }).strict();
    table2 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), index2),
      foreignKeys: recordType(stringType(), fk2),
      compositePrimaryKeys: recordType(stringType(), compositePK2),
      uniqueConstraints: recordType(stringType(), uniqueConstraint2).default({}),
      checkConstraint: recordType(stringType(), checkConstraint2).default({})
    }).strict();
    viewMeta = objectType({
      algorithm: enumType(["undefined", "merge", "temptable"]),
      sqlSecurity: enumType(["definer", "invoker"]),
      withCheckOption: enumType(["local", "cascaded"]).optional()
    }).strict();
    view2 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column2),
      definition: stringType().optional(),
      isExisting: booleanType()
    }).strict().merge(viewMeta);
    kitInternals2 = objectType({
      tables: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({ isDefaultAnExpression: booleanType().optional() }).optional()
          )
        }).optional()
      ).optional(),
      indexes: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({ isExpression: booleanType().optional() }).optional()
          )
        }).optional()
      ).optional()
    }).optional();
    dialect = literalType("mysql");
    schemaHash2 = objectType({
      id: stringType(),
      prevId: stringType()
    });
    schemaInternalV3 = objectType({
      version: literalType("3"),
      dialect,
      tables: recordType(stringType(), tableV3)
    }).strict();
    schemaInternalV4 = objectType({
      version: literalType("4"),
      dialect,
      tables: recordType(stringType(), tableV4),
      schemas: recordType(stringType(), stringType())
    }).strict();
    schemaInternalV5 = objectType({
      version: literalType("5"),
      dialect,
      tables: recordType(stringType(), table2),
      schemas: recordType(stringType(), stringType()),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals2
    }).strict();
    schemaInternal = objectType({
      version: literalType("5"),
      dialect,
      tables: recordType(stringType(), table2),
      views: recordType(stringType(), view2).default({}),
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals2
    }).strict();
    schemaV3 = schemaInternalV3.merge(schemaHash2);
    schemaV4 = schemaInternalV4.merge(schemaHash2);
    schemaV5 = schemaInternalV5.merge(schemaHash2);
    schema = schemaInternal.merge(schemaHash2);
    tableSquashedV4 = objectType({
      name: stringType(),
      schema: stringType().optional(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType())
    }).strict();
    tableSquashed2 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column2),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()).default({}),
      checkConstraints: recordType(stringType(), stringType()).default({})
    }).strict();
    viewSquashed = view2.omit({
      algorithm: true,
      sqlSecurity: true,
      withCheckOption: true
    }).extend({ meta: stringType() });
    schemaSquashed = objectType({
      version: literalType("5"),
      dialect,
      tables: recordType(stringType(), tableSquashed2),
      views: recordType(stringType(), viewSquashed)
    }).strict();
    schemaSquashedV4 = objectType({
      version: literalType("4"),
      dialect,
      tables: recordType(stringType(), tableSquashedV4),
      schemas: recordType(stringType(), stringType())
    }).strict();
    MySqlSquasher = {
      squashIdx: (idx) => {
        index2.parse(idx);
        return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.using ?? ""};${idx.algorithm ?? ""};${idx.lock ?? ""}`;
      },
      unsquashIdx: (input) => {
        const [name2, columnsString, isUnique, using, algorithm, lock] = input.split(";");
        const destructed = {
          name: name2,
          columns: columnsString.split(","),
          isUnique: isUnique === "true",
          using: using ? using : void 0,
          algorithm: algorithm ? algorithm : void 0,
          lock: lock ? lock : void 0
        };
        return index2.parse(destructed);
      },
      squashPK: (pk) => {
        return `${pk.name};${pk.columns.join(",")}`;
      },
      unsquashPK: (pk) => {
        const splitted = pk.split(";");
        return { name: splitted[0], columns: splitted[1].split(",") };
      },
      squashUnique: (unq) => {
        return `${unq.name};${unq.columns.join(",")}`;
      },
      unsquashUnique: (unq) => {
        const [name2, columns] = unq.split(";");
        return { name: name2, columns: columns.split(",") };
      },
      squashFK: (fk5) => {
        return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`;
      },
      unsquashFK: (input) => {
        const [
          name2,
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete
        ] = input.split(";");
        const result = fk2.parse({
          name: name2,
          tableFrom,
          columnsFrom: columnsFromStr.split(","),
          tableTo,
          columnsTo: columnsToStr.split(","),
          onUpdate,
          onDelete
        });
        return result;
      },
      squashCheck: (input) => {
        return `${input.name};${input.value}`;
      },
      unsquashCheck: (input) => {
        const [name2, value] = input.split(";");
        return { name: name2, value };
      },
      squashView: (view5) => {
        return `${view5.algorithm};${view5.sqlSecurity};${view5.withCheckOption}`;
      },
      unsquashView: (meta) => {
        const [algorithm, sqlSecurity, withCheckOption] = meta.split(";");
        const toReturn = {
          algorithm,
          sqlSecurity,
          withCheckOption: withCheckOption !== "undefined" ? withCheckOption : void 0
        };
        return viewMeta.parse(toReturn);
      }
    };
    squashMysqlScheme = (json4) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json4.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index6) => {
            return MySqlSquasher.squashIdx(index6);
          });
          const squashedFKs = mapValues(it[1].foreignKeys, (fk5) => {
            return MySqlSquasher.squashFK(fk5);
          });
          const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
            return MySqlSquasher.squashPK(pk);
          });
          const squashedUniqueConstraints = mapValues(
            it[1].uniqueConstraints,
            (unq) => {
              return MySqlSquasher.squashUnique(unq);
            }
          );
          const squashedCheckConstraints = mapValues(it[1].checkConstraint, (check) => {
            return MySqlSquasher.squashCheck(check);
          });
          return [
            it[0],
            {
              name: it[1].name,
              columns: it[1].columns,
              indexes: squashedIndexes,
              foreignKeys: squashedFKs,
              compositePrimaryKeys: squashedPKs,
              uniqueConstraints: squashedUniqueConstraints,
              checkConstraints: squashedCheckConstraints
            }
          ];
        })
      );
      const mappedViews = Object.fromEntries(
        Object.entries(json4.views).map(([key, value]) => {
          const meta = MySqlSquasher.squashView(value);
          return [key, {
            name: value.name,
            isExisting: value.isExisting,
            columns: value.columns,
            definition: value.definition,
            meta
          }];
        })
      );
      return {
        version: "5",
        dialect: json4.dialect,
        tables: mappedTables,
        views: mappedViews
      };
    };
    mysqlSchema = schema;
    mysqlSchemaV5 = schemaV5;
    mysqlSchemaSquashed = schemaSquashed;
    backwardCompatibleMysqlSchema = unionType([mysqlSchemaV5, schema]);
    dryMySql = mysqlSchema.parse({
      version: "5",
      dialect: "mysql",
      id: originUUID,
      prevId: "",
      tables: {},
      schemas: {},
      views: {},
      _meta: {
        schemas: {},
        tables: {},
        columns: {}
      }
    });
  }
});

// src/serializer/pgSchema.ts
var indexV2, columnV2, tableV2, enumSchemaV12, enumSchema2, pgSchemaV2, references, columnV1, tableV1, pgSchemaV1, indexColumn2, index3, indexV4, indexV5, indexV6, fk3, sequenceSchema2, roleSchema2, sequenceSquashed2, columnV7, column3, checkConstraint3, columnSquashed2, tableV32, compositePK3, uniqueConstraint3, policy2, policySquashed2, viewWithOption2, matViewWithOption2, mergedViewWithOption2, view3, tableV42, tableV5, tableV6, tableV7, table3, schemaHash3, kitInternals3, pgSchemaInternalV3, pgSchemaInternalV4, pgSchemaInternalV5, pgSchemaInternalV6, pgSchemaExternal, pgSchemaInternalV7, pgSchemaInternal, tableSquashed3, tableSquashedV42, pgSchemaSquashedV4, pgSchemaSquashedV6, pgSchemaSquashed, pgSchemaV3, pgSchemaV4, pgSchemaV5, pgSchemaV6, pgSchemaV7, pgSchema, backwardCompatiblePgSchema, PgSquasher, squashPgScheme, dryPg;
var init_pgSchema = __esm({
  "src/serializer/pgSchema.ts"() {
    "use strict";
    init_global();
    init_esm();
    indexV2 = objectType({
      name: stringType(),
      columns: recordType(
        stringType(),
        objectType({
          name: stringType()
        })
      ),
      isUnique: booleanType()
    }).strict();
    columnV2 = objectType({
      name: stringType(),
      type: stringType(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      references: stringType().optional()
    }).strict();
    tableV2 = objectType({
      name: stringType(),
      columns: recordType(stringType(), columnV2),
      indexes: recordType(stringType(), indexV2)
    }).strict();
    enumSchemaV12 = objectType({
      name: stringType(),
      values: recordType(stringType(), stringType())
    }).strict();
    enumSchema2 = objectType({
      name: stringType(),
      schema: stringType(),
      values: stringType().array()
    }).strict();
    pgSchemaV2 = objectType({
      version: literalType("2"),
      tables: recordType(stringType(), tableV2),
      enums: recordType(stringType(), enumSchemaV12)
    }).strict();
    references = objectType({
      foreignKeyName: stringType(),
      table: stringType(),
      column: stringType(),
      onDelete: stringType().optional(),
      onUpdate: stringType().optional()
    }).strict();
    columnV1 = objectType({
      name: stringType(),
      type: stringType(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      references: references.optional()
    }).strict();
    tableV1 = objectType({
      name: stringType(),
      columns: recordType(stringType(), columnV1),
      indexes: recordType(stringType(), indexV2)
    }).strict();
    pgSchemaV1 = objectType({
      version: literalType("1"),
      tables: recordType(stringType(), tableV1),
      enums: recordType(stringType(), enumSchemaV12)
    }).strict();
    indexColumn2 = objectType({
      expression: stringType(),
      isExpression: booleanType(),
      asc: booleanType(),
      nulls: stringType().optional(),
      opclass: stringType().optional()
    });
    index3 = objectType({
      name: stringType(),
      columns: indexColumn2.array(),
      isUnique: booleanType(),
      with: recordType(stringType(), anyType()).optional(),
      method: stringType().default("btree"),
      where: stringType().optional(),
      concurrently: booleanType().default(false)
    }).strict();
    indexV4 = objectType({
      name: stringType(),
      columns: stringType().array(),
      isUnique: booleanType(),
      with: recordType(stringType(), stringType()).optional(),
      method: stringType().default("btree"),
      where: stringType().optional(),
      concurrently: booleanType().default(false)
    }).strict();
    indexV5 = objectType({
      name: stringType(),
      columns: stringType().array(),
      isUnique: booleanType(),
      with: recordType(stringType(), stringType()).optional(),
      method: stringType().default("btree"),
      where: stringType().optional(),
      concurrently: booleanType().default(false)
    }).strict();
    indexV6 = objectType({
      name: stringType(),
      columns: stringType().array(),
      isUnique: booleanType(),
      with: recordType(stringType(), stringType()).optional(),
      method: stringType().default("btree"),
      where: stringType().optional(),
      concurrently: booleanType().default(false)
    }).strict();
    fk3 = objectType({
      name: stringType(),
      tableFrom: stringType(),
      columnsFrom: stringType().array(),
      tableTo: stringType(),
      schemaTo: stringType().optional(),
      columnsTo: stringType().array(),
      onUpdate: stringType().optional(),
      onDelete: stringType().optional()
    }).strict();
    sequenceSchema2 = objectType({
      name: stringType(),
      increment: stringType().optional(),
      minValue: stringType().optional(),
      maxValue: stringType().optional(),
      startWith: stringType().optional(),
      cache: stringType().optional(),
      cycle: booleanType().optional(),
      schema: stringType()
    }).strict();
    roleSchema2 = objectType({
      name: stringType(),
      createDb: booleanType().optional(),
      createRole: booleanType().optional(),
      inherit: booleanType().optional()
    }).strict();
    sequenceSquashed2 = objectType({
      name: stringType(),
      schema: stringType(),
      values: stringType()
    }).strict();
    columnV7 = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional()
    }).strict();
    column3 = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional(),
      generated: objectType({
        type: literalType("stored"),
        as: stringType()
      }).optional(),
      identity: sequenceSchema2.merge(objectType({ type: enumType(["always", "byDefault"]) })).optional()
    }).strict();
    checkConstraint3 = objectType({
      name: stringType(),
      value: stringType()
    }).strict();
    columnSquashed2 = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      default: anyType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional(),
      generated: objectType({
        type: literalType("stored"),
        as: stringType()
      }).optional(),
      identity: stringType().optional()
    }).strict();
    tableV32 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), index3),
      foreignKeys: recordType(stringType(), fk3)
    }).strict();
    compositePK3 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    uniqueConstraint3 = objectType({
      name: stringType(),
      columns: stringType().array(),
      nullsNotDistinct: booleanType()
    }).strict();
    policy2 = objectType({
      name: stringType(),
      as: enumType(["PERMISSIVE", "RESTRICTIVE"]).optional(),
      for: enumType(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional(),
      to: stringType().array().optional(),
      using: stringType().optional(),
      withCheck: stringType().optional(),
      on: stringType().optional(),
      schema: stringType().optional()
    }).strict();
    policySquashed2 = objectType({
      name: stringType(),
      values: stringType()
    }).strict();
    viewWithOption2 = objectType({
      checkOption: enumType(["local", "cascaded"]).optional(),
      securityBarrier: booleanType().optional(),
      securityInvoker: booleanType().optional()
    }).strict();
    matViewWithOption2 = objectType({
      fillfactor: numberType().optional(),
      toastTupleTarget: numberType().optional(),
      parallelWorkers: numberType().optional(),
      autovacuumEnabled: booleanType().optional(),
      vacuumIndexCleanup: enumType(["auto", "off", "on"]).optional(),
      vacuumTruncate: booleanType().optional(),
      autovacuumVacuumThreshold: numberType().optional(),
      autovacuumVacuumScaleFactor: numberType().optional(),
      autovacuumVacuumCostDelay: numberType().optional(),
      autovacuumVacuumCostLimit: numberType().optional(),
      autovacuumFreezeMinAge: numberType().optional(),
      autovacuumFreezeMaxAge: numberType().optional(),
      autovacuumFreezeTableAge: numberType().optional(),
      autovacuumMultixactFreezeMinAge: numberType().optional(),
      autovacuumMultixactFreezeMaxAge: numberType().optional(),
      autovacuumMultixactFreezeTableAge: numberType().optional(),
      logAutovacuumMinDuration: numberType().optional(),
      userCatalogTable: booleanType().optional()
    }).strict();
    mergedViewWithOption2 = viewWithOption2.merge(matViewWithOption2).strict();
    view3 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column3),
      definition: stringType().optional(),
      materialized: booleanType(),
      with: mergedViewWithOption2.optional(),
      isExisting: booleanType(),
      withNoData: booleanType().optional(),
      using: stringType().optional(),
      tablespace: stringType().optional()
    }).strict();
    tableV42 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), indexV4),
      foreignKeys: recordType(stringType(), fk3)
    }).strict();
    tableV5 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), indexV5),
      foreignKeys: recordType(stringType(), fk3),
      compositePrimaryKeys: recordType(stringType(), compositePK3),
      uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
    }).strict();
    tableV6 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), indexV6),
      foreignKeys: recordType(stringType(), fk3),
      compositePrimaryKeys: recordType(stringType(), compositePK3),
      uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
    }).strict();
    tableV7 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), columnV7),
      indexes: recordType(stringType(), index3),
      foreignKeys: recordType(stringType(), fk3),
      compositePrimaryKeys: recordType(stringType(), compositePK3),
      uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({})
    }).strict();
    table3 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), index3),
      foreignKeys: recordType(stringType(), fk3),
      compositePrimaryKeys: recordType(stringType(), compositePK3),
      uniqueConstraints: recordType(stringType(), uniqueConstraint3).default({}),
      policies: recordType(stringType(), policy2).default({}),
      checkConstraints: recordType(stringType(), checkConstraint3).default({}),
      isRLSEnabled: booleanType().default(false)
    }).strict();
    schemaHash3 = objectType({
      id: stringType(),
      prevId: stringType()
    });
    kitInternals3 = objectType({
      tables: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({
              isArray: booleanType().optional(),
              dimensions: numberType().optional(),
              rawType: stringType().optional(),
              isDefaultAnExpression: booleanType().optional()
            }).optional()
          )
        }).optional()
      )
    }).optional();
    pgSchemaInternalV3 = objectType({
      version: literalType("3"),
      dialect: literalType("pg"),
      tables: recordType(stringType(), tableV32),
      enums: recordType(stringType(), enumSchemaV12)
    }).strict();
    pgSchemaInternalV4 = objectType({
      version: literalType("4"),
      dialect: literalType("pg"),
      tables: recordType(stringType(), tableV42),
      enums: recordType(stringType(), enumSchemaV12),
      schemas: recordType(stringType(), stringType())
    }).strict();
    pgSchemaInternalV5 = objectType({
      version: literalType("5"),
      dialect: literalType("pg"),
      tables: recordType(stringType(), tableV5),
      enums: recordType(stringType(), enumSchemaV12),
      schemas: recordType(stringType(), stringType()),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals3
    }).strict();
    pgSchemaInternalV6 = objectType({
      version: literalType("6"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), tableV6),
      enums: recordType(stringType(), enumSchema2),
      schemas: recordType(stringType(), stringType()),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals3
    }).strict();
    pgSchemaExternal = objectType({
      version: literalType("5"),
      dialect: literalType("pg"),
      tables: arrayType(table3),
      enums: arrayType(enumSchemaV12),
      schemas: arrayType(objectType({ name: stringType() })),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      })
    }).strict();
    pgSchemaInternalV7 = objectType({
      version: literalType("7"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), tableV7),
      enums: recordType(stringType(), enumSchema2),
      schemas: recordType(stringType(), stringType()),
      sequences: recordType(stringType(), sequenceSchema2),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals3
    }).strict();
    pgSchemaInternal = objectType({
      version: literalType("7"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), table3),
      enums: recordType(stringType(), enumSchema2),
      schemas: recordType(stringType(), stringType()),
      views: recordType(stringType(), view3).default({}),
      sequences: recordType(stringType(), sequenceSchema2).default({}),
      roles: recordType(stringType(), roleSchema2).default({}),
      policies: recordType(stringType(), policy2).default({}),
      _meta: objectType({
        schemas: recordType(stringType(), stringType()),
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals3
    }).strict();
    tableSquashed3 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), columnSquashed2),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()),
      policies: recordType(stringType(), stringType()),
      checkConstraints: recordType(stringType(), stringType()),
      isRLSEnabled: booleanType().default(false)
    }).strict();
    tableSquashedV42 = objectType({
      name: stringType(),
      schema: stringType(),
      columns: recordType(stringType(), column3),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType())
    }).strict();
    pgSchemaSquashedV4 = objectType({
      version: literalType("4"),
      dialect: literalType("pg"),
      tables: recordType(stringType(), tableSquashedV42),
      enums: recordType(stringType(), enumSchemaV12),
      schemas: recordType(stringType(), stringType())
    }).strict();
    pgSchemaSquashedV6 = objectType({
      version: literalType("6"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), tableSquashed3),
      enums: recordType(stringType(), enumSchema2),
      schemas: recordType(stringType(), stringType())
    }).strict();
    pgSchemaSquashed = objectType({
      version: literalType("7"),
      dialect: literalType("postgresql"),
      tables: recordType(stringType(), tableSquashed3),
      enums: recordType(stringType(), enumSchema2),
      schemas: recordType(stringType(), stringType()),
      views: recordType(stringType(), view3),
      sequences: recordType(stringType(), sequenceSquashed2),
      roles: recordType(stringType(), roleSchema2).default({}),
      policies: recordType(stringType(), policySquashed2).default({})
    }).strict();
    pgSchemaV3 = pgSchemaInternalV3.merge(schemaHash3);
    pgSchemaV4 = pgSchemaInternalV4.merge(schemaHash3);
    pgSchemaV5 = pgSchemaInternalV5.merge(schemaHash3);
    pgSchemaV6 = pgSchemaInternalV6.merge(schemaHash3);
    pgSchemaV7 = pgSchemaInternalV7.merge(schemaHash3);
    pgSchema = pgSchemaInternal.merge(schemaHash3);
    backwardCompatiblePgSchema = unionType([
      pgSchemaV5,
      pgSchemaV6,
      pgSchema
    ]);
    PgSquasher = {
      squashIdx: (idx) => {
        index3.parse(idx);
        return `${idx.name};${idx.columns.map(
          (c) => `${c.expression}--${c.isExpression}--${c.asc}--${c.nulls}--${c.opclass ? c.opclass : ""}`
        ).join(",,")};${idx.isUnique};${idx.concurrently};${idx.method};${idx.where};${JSON.stringify(idx.with)}`;
      },
      unsquashIdx: (input) => {
        const [
          name2,
          columnsString,
          isUnique,
          concurrently,
          method,
          where,
          idxWith
        ] = input.split(";");
        const columnString = columnsString.split(",,");
        const columns = [];
        for (const column6 of columnString) {
          const [expression, isExpression, asc2, nulls, opclass] = column6.split("--");
          columns.push({
            nulls,
            isExpression: isExpression === "true",
            asc: asc2 === "true",
            expression,
            opclass: opclass === "undefined" ? void 0 : opclass
          });
        }
        const result = index3.parse({
          name: name2,
          columns,
          isUnique: isUnique === "true",
          concurrently: concurrently === "true",
          method,
          where: where === "undefined" ? void 0 : where,
          with: !idxWith || idxWith === "undefined" ? void 0 : JSON.parse(idxWith)
        });
        return result;
      },
      squashIdxPush: (idx) => {
        index3.parse(idx);
        return `${idx.name};${idx.columns.map((c) => `${c.isExpression ? "" : c.expression}--${c.asc}--${c.nulls}`).join(",,")};${idx.isUnique};${idx.method};${JSON.stringify(idx.with)}`;
      },
      unsquashIdxPush: (input) => {
        const [name2, columnsString, isUnique, method, idxWith] = input.split(";");
        const columnString = columnsString.split("--");
        const columns = [];
        for (const column6 of columnString) {
          const [expression, asc2, nulls, opclass] = column6.split(",");
          columns.push({
            nulls,
            isExpression: expression === "",
            asc: asc2 === "true",
            expression
          });
        }
        const result = index3.parse({
          name: name2,
          columns,
          isUnique: isUnique === "true",
          concurrently: false,
          method,
          with: idxWith === "undefined" ? void 0 : JSON.parse(idxWith)
        });
        return result;
      },
      squashFK: (fk5) => {
        return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""};${fk5.schemaTo || "public"}`;
      },
      squashPolicy: (policy5) => {
        return `${policy5.name}--${policy5.as}--${policy5.for}--${policy5.to?.join(",")}--${policy5.using}--${policy5.withCheck}--${policy5.on}`;
      },
      unsquashPolicy: (policy5) => {
        const splitted = policy5.split("--");
        return {
          name: splitted[0],
          as: splitted[1],
          for: splitted[2],
          to: splitted[3].split(","),
          using: splitted[4] !== "undefined" ? splitted[4] : void 0,
          withCheck: splitted[5] !== "undefined" ? splitted[5] : void 0,
          on: splitted[6] !== "undefined" ? splitted[6] : void 0
        };
      },
      squashPolicyPush: (policy5) => {
        return `${policy5.name}--${policy5.as}--${policy5.for}--${policy5.to?.join(",")}--${policy5.on}`;
      },
      unsquashPolicyPush: (policy5) => {
        const splitted = policy5.split("--");
        return {
          name: splitted[0],
          as: splitted[1],
          for: splitted[2],
          to: splitted[3].split(","),
          on: splitted[4] !== "undefined" ? splitted[4] : void 0
        };
      },
      squashPK: (pk) => {
        return `${pk.columns.join(",")};${pk.name}`;
      },
      unsquashPK: (pk) => {
        const splitted = pk.split(";");
        return { name: splitted[1], columns: splitted[0].split(",") };
      },
      squashUnique: (unq) => {
        return `${unq.name};${unq.columns.join(",")};${unq.nullsNotDistinct}`;
      },
      unsquashUnique: (unq) => {
        const [name2, columns, nullsNotDistinct] = unq.split(";");
        return {
          name: name2,
          columns: columns.split(","),
          nullsNotDistinct: nullsNotDistinct === "true"
        };
      },
      unsquashFK: (input) => {
        const [
          name2,
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete,
          schemaTo
        ] = input.split(";");
        const result = fk3.parse({
          name: name2,
          tableFrom,
          columnsFrom: columnsFromStr.split(","),
          schemaTo,
          tableTo,
          columnsTo: columnsToStr.split(","),
          onUpdate,
          onDelete
        });
        return result;
      },
      squashSequence: (seq) => {
        return `${seq.minValue};${seq.maxValue};${seq.increment};${seq.startWith};${seq.cache};${seq.cycle ?? ""}`;
      },
      unsquashSequence: (seq) => {
        const splitted = seq.split(";");
        return {
          minValue: splitted[0] !== "undefined" ? splitted[0] : void 0,
          maxValue: splitted[1] !== "undefined" ? splitted[1] : void 0,
          increment: splitted[2] !== "undefined" ? splitted[2] : void 0,
          startWith: splitted[3] !== "undefined" ? splitted[3] : void 0,
          cache: splitted[4] !== "undefined" ? splitted[4] : void 0,
          cycle: splitted[5] === "true"
        };
      },
      squashIdentity: (seq) => {
        return `${seq.name};${seq.type};${seq.minValue};${seq.maxValue};${seq.increment};${seq.startWith};${seq.cache};${seq.cycle ?? ""}`;
      },
      unsquashIdentity: (seq) => {
        const splitted = seq.split(";");
        return {
          name: splitted[0],
          type: splitted[1],
          minValue: splitted[2] !== "undefined" ? splitted[2] : void 0,
          maxValue: splitted[3] !== "undefined" ? splitted[3] : void 0,
          increment: splitted[4] !== "undefined" ? splitted[4] : void 0,
          startWith: splitted[5] !== "undefined" ? splitted[5] : void 0,
          cache: splitted[6] !== "undefined" ? splitted[6] : void 0,
          cycle: splitted[7] === "true"
        };
      },
      squashCheck: (check) => {
        return `${check.name};${check.value}`;
      },
      unsquashCheck: (input) => {
        const [
          name2,
          value
        ] = input.split(";");
        return { name: name2, value };
      }
    };
    squashPgScheme = (json4, action) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json4.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index6) => {
            return action === "push" ? PgSquasher.squashIdxPush(index6) : PgSquasher.squashIdx(index6);
          });
          const squashedFKs = mapValues(it[1].foreignKeys, (fk5) => {
            return PgSquasher.squashFK(fk5);
          });
          const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
            return PgSquasher.squashPK(pk);
          });
          const mappedColumns = Object.fromEntries(
            Object.entries(it[1].columns).map((it2) => {
              const mappedIdentity = it2[1].identity ? PgSquasher.squashIdentity(it2[1].identity) : void 0;
              return [
                it2[0],
                {
                  ...it2[1],
                  identity: mappedIdentity
                }
              ];
            })
          );
          const squashedUniqueConstraints = mapValues(
            it[1].uniqueConstraints,
            (unq) => {
              return PgSquasher.squashUnique(unq);
            }
          );
          const squashedPolicies = mapValues(it[1].policies, (policy5) => {
            return action === "push" ? PgSquasher.squashPolicyPush(policy5) : PgSquasher.squashPolicy(policy5);
          });
          const squashedChecksContraints = mapValues(
            it[1].checkConstraints,
            (check) => {
              return PgSquasher.squashCheck(check);
            }
          );
          return [
            it[0],
            {
              name: it[1].name,
              schema: it[1].schema,
              columns: mappedColumns,
              indexes: squashedIndexes,
              foreignKeys: squashedFKs,
              compositePrimaryKeys: squashedPKs,
              uniqueConstraints: squashedUniqueConstraints,
              policies: squashedPolicies,
              checkConstraints: squashedChecksContraints,
              isRLSEnabled: it[1].isRLSEnabled ?? false
            }
          ];
        })
      );
      const mappedSequences = Object.fromEntries(
        Object.entries(json4.sequences).map((it) => {
          return [
            it[0],
            {
              name: it[1].name,
              schema: it[1].schema,
              values: PgSquasher.squashSequence(it[1])
            }
          ];
        })
      );
      const mappedPolicies = Object.fromEntries(
        Object.entries(json4.policies).map((it) => {
          return [
            it[0],
            {
              name: it[1].name,
              values: action === "push" ? PgSquasher.squashPolicyPush(it[1]) : PgSquasher.squashPolicy(it[1])
            }
          ];
        })
      );
      return {
        version: "7",
        dialect: json4.dialect,
        tables: mappedTables,
        enums: json4.enums,
        schemas: json4.schemas,
        views: json4.views,
        policies: mappedPolicies,
        sequences: mappedSequences,
        roles: json4.roles
      };
    };
    dryPg = pgSchema.parse({
      version: snapshotVersion,
      dialect: "postgresql",
      id: originUUID,
      prevId: "",
      tables: {},
      enums: {},
      schemas: {},
      policies: {},
      roles: {},
      sequences: {},
      _meta: {
        schemas: {},
        tables: {},
        columns: {}
      }
    });
  }
});

// src/serializer/singlestoreSchema.ts
var index4, column4, compositePK4, uniqueConstraint4, table4, viewMeta2, kitInternals4, dialect2, schemaHash4, schemaInternal2, schema2, tableSquashed4, schemaSquashed2, SingleStoreSquasher, squashSingleStoreScheme, singlestoreSchema, singlestoreSchemaSquashed, backwardCompatibleSingleStoreSchema, drySingleStore;
var init_singlestoreSchema = __esm({
  "src/serializer/singlestoreSchema.ts"() {
    "use strict";
    init_esm();
    init_global();
    index4 = objectType({
      name: stringType(),
      columns: stringType().array(),
      isUnique: booleanType(),
      using: enumType(["btree", "hash"]).optional(),
      algorithm: enumType(["default", "inplace", "copy"]).optional(),
      lock: enumType(["default", "none", "shared", "exclusive"]).optional()
    }).strict();
    column4 = objectType({
      name: stringType(),
      type: stringType(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      autoincrement: booleanType().optional(),
      default: anyType().optional(),
      onUpdate: anyType().optional(),
      generated: objectType({
        type: enumType(["stored", "virtual"]),
        as: stringType()
      }).optional()
    }).strict();
    compositePK4 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    uniqueConstraint4 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    table4 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column4),
      indexes: recordType(stringType(), index4),
      compositePrimaryKeys: recordType(stringType(), compositePK4),
      uniqueConstraints: recordType(stringType(), uniqueConstraint4).default({})
    }).strict();
    viewMeta2 = objectType({
      algorithm: enumType(["undefined", "merge", "temptable"]),
      sqlSecurity: enumType(["definer", "invoker"]),
      withCheckOption: enumType(["local", "cascaded"]).optional()
    }).strict();
    kitInternals4 = objectType({
      tables: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({ isDefaultAnExpression: booleanType().optional() }).optional()
          )
        }).optional()
      ).optional(),
      indexes: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({ isExpression: booleanType().optional() }).optional()
          )
        }).optional()
      ).optional()
    }).optional();
    dialect2 = literalType("singlestore");
    schemaHash4 = objectType({
      id: stringType(),
      prevId: stringType()
    });
    schemaInternal2 = objectType({
      version: literalType("1"),
      dialect: dialect2,
      tables: recordType(stringType(), table4),
      /* views: record(string(), view).default({}), */
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals4
    }).strict();
    schema2 = schemaInternal2.merge(schemaHash4);
    tableSquashed4 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column4),
      indexes: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()).default({})
    }).strict();
    schemaSquashed2 = objectType({
      version: literalType("1"),
      dialect: dialect2,
      tables: recordType(stringType(), tableSquashed4)
      /* views: record(string(), viewSquashed), */
    }).strict();
    SingleStoreSquasher = {
      squashIdx: (idx) => {
        index4.parse(idx);
        return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.using ?? ""};${idx.algorithm ?? ""};${idx.lock ?? ""}`;
      },
      unsquashIdx: (input) => {
        const [name2, columnsString, isUnique, using, algorithm, lock] = input.split(";");
        const destructed = {
          name: name2,
          columns: columnsString.split(","),
          isUnique: isUnique === "true",
          using: using ? using : void 0,
          algorithm: algorithm ? algorithm : void 0,
          lock: lock ? lock : void 0
        };
        return index4.parse(destructed);
      },
      squashPK: (pk) => {
        return `${pk.name};${pk.columns.join(",")}`;
      },
      unsquashPK: (pk) => {
        const splitted = pk.split(";");
        return { name: splitted[0], columns: splitted[1].split(",") };
      },
      squashUnique: (unq) => {
        return `${unq.name};${unq.columns.join(",")}`;
      },
      unsquashUnique: (unq) => {
        const [name2, columns] = unq.split(";");
        return { name: name2, columns: columns.split(",") };
      }
      /* squashView: (view: View): string => {
      		return `${view.algorithm};${view.sqlSecurity};${view.withCheckOption}`;
      	},
      	unsquashView: (meta: string): SquasherViewMeta => {
      		const [algorithm, sqlSecurity, withCheckOption] = meta.split(';');
      		const toReturn = {
      			algorithm: algorithm,
      			sqlSecurity: sqlSecurity,
      			withCheckOption: withCheckOption !== 'undefined' ? withCheckOption : undefined,
      		};
      
      		return viewMeta.parse(toReturn);
      	}, */
    };
    squashSingleStoreScheme = (json4) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json4.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index6) => {
            return SingleStoreSquasher.squashIdx(index6);
          });
          const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
            return SingleStoreSquasher.squashPK(pk);
          });
          const squashedUniqueConstraints = mapValues(
            it[1].uniqueConstraints,
            (unq) => {
              return SingleStoreSquasher.squashUnique(unq);
            }
          );
          return [
            it[0],
            {
              name: it[1].name,
              columns: it[1].columns,
              indexes: squashedIndexes,
              compositePrimaryKeys: squashedPKs,
              uniqueConstraints: squashedUniqueConstraints
            }
          ];
        })
      );
      return {
        version: "1",
        dialect: json4.dialect,
        tables: mappedTables
        /* views: mappedViews, */
      };
    };
    singlestoreSchema = schema2;
    singlestoreSchemaSquashed = schemaSquashed2;
    backwardCompatibleSingleStoreSchema = unionType([singlestoreSchema, schema2]);
    drySingleStore = singlestoreSchema.parse({
      version: "1",
      dialect: "singlestore",
      id: originUUID,
      prevId: "",
      tables: {},
      schemas: {},
      /* views: {}, */
      _meta: {
        schemas: {},
        tables: {},
        columns: {}
      }
    });
  }
});

// src/serializer/sqliteSchema.ts
var index5, fk4, compositePK5, column5, tableV33, uniqueConstraint5, checkConstraint4, table5, view4, dialect3, schemaHash5, schemaInternalV32, schemaInternalV42, schemaInternalV52, kitInternals5, latestVersion, schemaInternal3, schemaV32, schemaV42, schemaV52, schema3, tableSquashed5, schemaSquashed3, SQLiteSquasher, squashSqliteScheme, drySQLite, sqliteSchemaV5, sqliteSchema, SQLiteSchemaSquashed, backwardCompatibleSqliteSchema;
var init_sqliteSchema = __esm({
  "src/serializer/sqliteSchema.ts"() {
    "use strict";
    init_esm();
    init_global();
    index5 = objectType({
      name: stringType(),
      columns: stringType().array(),
      where: stringType().optional(),
      isUnique: booleanType()
    }).strict();
    fk4 = objectType({
      name: stringType(),
      tableFrom: stringType(),
      columnsFrom: stringType().array(),
      tableTo: stringType(),
      columnsTo: stringType().array(),
      onUpdate: stringType().optional(),
      onDelete: stringType().optional()
    }).strict();
    compositePK5 = objectType({
      columns: stringType().array(),
      name: stringType().optional()
    }).strict();
    column5 = objectType({
      name: stringType(),
      type: stringType(),
      primaryKey: booleanType(),
      notNull: booleanType(),
      autoincrement: booleanType().optional(),
      default: anyType().optional(),
      generated: objectType({
        type: enumType(["stored", "virtual"]),
        as: stringType()
      }).optional()
    }).strict();
    tableV33 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column5),
      indexes: recordType(stringType(), index5),
      foreignKeys: recordType(stringType(), fk4)
    }).strict();
    uniqueConstraint5 = objectType({
      name: stringType(),
      columns: stringType().array()
    }).strict();
    checkConstraint4 = objectType({
      name: stringType(),
      value: stringType()
    }).strict();
    table5 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column5),
      indexes: recordType(stringType(), index5),
      foreignKeys: recordType(stringType(), fk4),
      compositePrimaryKeys: recordType(stringType(), compositePK5),
      uniqueConstraints: recordType(stringType(), uniqueConstraint5).default({}),
      checkConstraints: recordType(stringType(), checkConstraint4).default({})
    }).strict();
    view4 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column5),
      definition: stringType().optional(),
      isExisting: booleanType()
    }).strict();
    dialect3 = enumType(["sqlite"]);
    schemaHash5 = objectType({
      id: stringType(),
      prevId: stringType()
    }).strict();
    schemaInternalV32 = objectType({
      version: literalType("3"),
      dialect: dialect3,
      tables: recordType(stringType(), tableV33),
      enums: objectType({})
    }).strict();
    schemaInternalV42 = objectType({
      version: literalType("4"),
      dialect: dialect3,
      tables: recordType(stringType(), table5),
      views: recordType(stringType(), view4).default({}),
      enums: objectType({})
    }).strict();
    schemaInternalV52 = objectType({
      version: literalType("5"),
      dialect: dialect3,
      tables: recordType(stringType(), table5),
      enums: objectType({}),
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      })
    }).strict();
    kitInternals5 = objectType({
      indexes: recordType(
        stringType(),
        objectType({
          columns: recordType(
            stringType(),
            objectType({ isExpression: booleanType().optional() }).optional()
          )
        }).optional()
      ).optional()
    }).optional();
    latestVersion = literalType("6");
    schemaInternal3 = objectType({
      version: latestVersion,
      dialect: dialect3,
      tables: recordType(stringType(), table5),
      views: recordType(stringType(), view4).default({}),
      enums: objectType({}),
      _meta: objectType({
        tables: recordType(stringType(), stringType()),
        columns: recordType(stringType(), stringType())
      }),
      internal: kitInternals5
    }).strict();
    schemaV32 = schemaInternalV32.merge(schemaHash5).strict();
    schemaV42 = schemaInternalV42.merge(schemaHash5).strict();
    schemaV52 = schemaInternalV52.merge(schemaHash5).strict();
    schema3 = schemaInternal3.merge(schemaHash5).strict();
    tableSquashed5 = objectType({
      name: stringType(),
      columns: recordType(stringType(), column5),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()),
      uniqueConstraints: recordType(stringType(), stringType()).default({}),
      checkConstraints: recordType(stringType(), stringType()).default({})
    }).strict();
    schemaSquashed3 = objectType({
      version: latestVersion,
      dialect: dialect3,
      tables: recordType(stringType(), tableSquashed5),
      views: recordType(stringType(), view4),
      enums: anyType()
    }).strict();
    SQLiteSquasher = {
      squashIdx: (idx) => {
        index5.parse(idx);
        return `${idx.name};${idx.columns.join(",")};${idx.isUnique};${idx.where ?? ""}`;
      },
      unsquashIdx: (input) => {
        const [name2, columnsString, isUnique, where] = input.split(";");
        const result = index5.parse({
          name: name2,
          columns: columnsString.split(","),
          isUnique: isUnique === "true",
          where: where ?? void 0
        });
        return result;
      },
      squashUnique: (unq) => {
        return `${unq.name};${unq.columns.join(",")}`;
      },
      unsquashUnique: (unq) => {
        const [name2, columns] = unq.split(";");
        return { name: name2, columns: columns.split(",") };
      },
      squashFK: (fk5) => {
        return `${fk5.name};${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`;
      },
      unsquashFK: (input) => {
        const [
          name2,
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete
        ] = input.split(";");
        const result = fk4.parse({
          name: name2,
          tableFrom,
          columnsFrom: columnsFromStr.split(","),
          tableTo,
          columnsTo: columnsToStr.split(","),
          onUpdate,
          onDelete
        });
        return result;
      },
      squashPushFK: (fk5) => {
        return `${fk5.tableFrom};${fk5.columnsFrom.join(",")};${fk5.tableTo};${fk5.columnsTo.join(",")};${fk5.onUpdate ?? ""};${fk5.onDelete ?? ""}`;
      },
      unsquashPushFK: (input) => {
        const [
          tableFrom,
          columnsFromStr,
          tableTo,
          columnsToStr,
          onUpdate,
          onDelete
        ] = input.split(";");
        const result = fk4.parse({
          name: "",
          tableFrom,
          columnsFrom: columnsFromStr.split(","),
          tableTo,
          columnsTo: columnsToStr.split(","),
          onUpdate,
          onDelete
        });
        return result;
      },
      squashPK: (pk) => {
        return pk.columns.join(",");
      },
      unsquashPK: (pk) => {
        return pk.split(",");
      },
      squashCheck: (check) => {
        return `${check.name};${check.value}`;
      },
      unsquashCheck: (input) => {
        const [
          name2,
          value
        ] = input.split(";");
        return { name: name2, value };
      }
    };
    squashSqliteScheme = (json4, action) => {
      const mappedTables = Object.fromEntries(
        Object.entries(json4.tables).map((it) => {
          const squashedIndexes = mapValues(it[1].indexes, (index6) => {
            return SQLiteSquasher.squashIdx(index6);
          });
          const squashedFKs = customMapEntries(
            it[1].foreignKeys,
            (key, value) => {
              return action === "push" ? [
                SQLiteSquasher.squashPushFK(value),
                SQLiteSquasher.squashPushFK(value)
              ] : [key, SQLiteSquasher.squashFK(value)];
            }
          );
          const squashedPKs = mapValues(it[1].compositePrimaryKeys, (pk) => {
            return SQLiteSquasher.squashPK(pk);
          });
          const squashedUniqueConstraints = mapValues(
            it[1].uniqueConstraints,
            (unq) => {
              return SQLiteSquasher.squashUnique(unq);
            }
          );
          const squashedCheckConstraints = mapValues(
            it[1].checkConstraints,
            (check) => {
              return SQLiteSquasher.squashCheck(check);
            }
          );
          return [
            it[0],
            {
              name: it[1].name,
              columns: it[1].columns,
              indexes: squashedIndexes,
              foreignKeys: squashedFKs,
              compositePrimaryKeys: squashedPKs,
              uniqueConstraints: squashedUniqueConstraints,
              checkConstraints: squashedCheckConstraints
            }
          ];
        })
      );
      return {
        version: "6",
        dialect: json4.dialect,
        tables: mappedTables,
        views: json4.views,
        enums: json4.enums
      };
    };
    drySQLite = schema3.parse({
      version: "6",
      dialect: "sqlite",
      id: originUUID,
      prevId: "",
      tables: {},
      views: {},
      enums: {},
      _meta: {
        tables: {},
        columns: {}
      }
    });
    sqliteSchemaV5 = schemaV52;
    sqliteSchema = schema3;
    SQLiteSchemaSquashed = schemaSquashed3;
    backwardCompatibleSqliteSchema = unionType([sqliteSchemaV5, schema3]);
  }
});

// src/utils.ts
function isPgArrayType(sqlType) {
  return sqlType.match(/.*\[\d*\].*|.*\[\].*/g) !== null;
}
function findAddedAndRemoved(columnNames1, columnNames2) {
  const set1 = new Set(columnNames1);
  const set2 = new Set(columnNames2);
  const addedColumns = columnNames2.filter((it) => !set1.has(it));
  const removedColumns = columnNames1.filter((it) => !set2.has(it));
  return { addedColumns, removedColumns };
}
function escapeSingleQuotes(str) {
  return str.replace(/'/g, "''");
}
var copy, prepareMigrationMeta, schemaRenameKey, tableRenameKey, columnRenameKey;
var init_utils = __esm({
  "src/utils.ts"() {
    "use strict";
    init_views();
    init_global();
    init_gelSchema();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    copy = (it) => {
      return JSON.parse(JSON.stringify(it));
    };
    prepareMigrationMeta = (schemas, tables, columns) => {
      const _meta = {
        schemas: {},
        tables: {},
        columns: {}
      };
      schemas.forEach((it) => {
        const from = schemaRenameKey(it.from);
        const to = schemaRenameKey(it.to);
        _meta.schemas[from] = to;
      });
      tables.forEach((it) => {
        const from = tableRenameKey(it.from);
        const to = tableRenameKey(it.to);
        _meta.tables[from] = to;
      });
      columns.forEach((it) => {
        const from = columnRenameKey(it.from.table, it.from.schema, it.from.column);
        const to = columnRenameKey(it.to.table, it.to.schema, it.to.column);
        _meta.columns[from] = to;
      });
      return _meta;
    };
    schemaRenameKey = (it) => {
      return it;
    };
    tableRenameKey = (it) => {
      const out = it.schema ? `"${it.schema}"."${it.name}"` : `"${it.name}"`;
      return out;
    };
    columnRenameKey = (table6, schema5, column6) => {
      const out = schema5 ? `"${schema5}"."${table6}"."${column6}"` : `"${table6}"."${column6}"`;
      return out;
    };
  }
});

// src/cli/views.ts
var import_hanji, warning, error, isRenamePromptItem, ResolveColumnSelect, tableKey, ResolveSelectNamed, ResolveSelect, ResolveSchemasSelect, Spinner, ProgressView;
var init_views = __esm({
  "src/cli/views.ts"() {
    "use strict";
    init_source();
    import_hanji = __toESM(require_hanji());
    init_utils();
    warning = (msg) => {
      (0, import_hanji.render)(`[${source_default.yellow("Warning")}] ${msg}`);
    };
    error = (error2, greyMsg = "") => {
      return `${source_default.bgRed.bold(" Error ")} ${error2} ${greyMsg ? source_default.grey(greyMsg) : ""}`.trim();
    };
    isRenamePromptItem = (item) => {
      return "from" in item && "to" in item;
    };
    ResolveColumnSelect = class extends import_hanji.Prompt {
      constructor(tableName, base, data) {
        super();
        this.tableName = tableName;
        this.base = base;
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.data = new import_hanji.SelectState(data);
        this.data.bind(this);
      }
      render(status) {
        if (status === "submitted" || status === "aborted") {
          return "\n";
        }
        let text5 = `
Is ${source_default.bold.blue(
          this.base.name
        )} column in ${source_default.bold.blue(
          this.tableName
        )} table created or renamed from another column?
`;
        const isSelectedRenamed = isRenamePromptItem(
          this.data.items[this.data.selectedIdx]
        );
        const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
        const labelLength = this.data.items.filter((it) => isRenamePromptItem(it)).map((it) => {
          return this.base.name.length + 3 + it["from"].name.length;
        }).reduce((a, b) => {
          if (a > b) {
            return a;
          }
          return b;
        }, 0);
        this.data.items.forEach((it, idx) => {
          const isSelected = idx === this.data.selectedIdx;
          const isRenamed = isRenamePromptItem(it);
          const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
          const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray("rename column")}` : `${source_default.green("+")} ${title} ${source_default.gray("create column")}`;
          text5 += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text5 += idx != this.data.items.length - 1 ? "\n" : "";
        });
        return text5;
      }
      result() {
        return this.data.items[this.data.selectedIdx];
      }
    };
    tableKey = (it) => {
      return it.schema === "public" || !it.schema ? it.name : `${it.schema}.${it.name}`;
    };
    ResolveSelectNamed = class extends import_hanji.Prompt {
      constructor(base, data, entityType) {
        super();
        this.base = base;
        this.entityType = entityType;
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.state = new import_hanji.SelectState(data);
        this.state.bind(this);
        this.base = base;
      }
      render(status) {
        if (status === "submitted" || status === "aborted") {
          return "";
        }
        const key = this.base.name;
        let text5 = `
Is ${source_default.bold.blue(key)} ${this.entityType} created or renamed from another ${this.entityType}?
`;
        const isSelectedRenamed = isRenamePromptItem(
          this.state.items[this.state.selectedIdx]
        );
        const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
        const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((_2) => {
          const it = _2;
          const keyFrom = it.from.name;
          return key.length + 3 + keyFrom.length;
        }).reduce((a, b) => {
          if (a > b) {
            return a;
          }
          return b;
        }, 0);
        const entityType = this.entityType;
        this.state.items.forEach((it, idx) => {
          const isSelected = idx === this.state.selectedIdx;
          const isRenamed = isRenamePromptItem(it);
          const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
          const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray(`rename ${entityType}`)}` : `${source_default.green("+")} ${title} ${source_default.gray(`create ${entityType}`)}`;
          text5 += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text5 += idx != this.state.items.length - 1 ? "\n" : "";
        });
        return text5;
      }
      result() {
        return this.state.items[this.state.selectedIdx];
      }
    };
    ResolveSelect = class extends import_hanji.Prompt {
      constructor(base, data, entityType) {
        super();
        this.base = base;
        this.entityType = entityType;
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.state = new import_hanji.SelectState(data);
        this.state.bind(this);
        this.base = base;
      }
      render(status) {
        if (status === "submitted" || status === "aborted") {
          return "";
        }
        const key = tableKey(this.base);
        let text5 = `
Is ${source_default.bold.blue(key)} ${this.entityType} created or renamed from another ${this.entityType}?
`;
        const isSelectedRenamed = isRenamePromptItem(
          this.state.items[this.state.selectedIdx]
        );
        const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
        const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((_2) => {
          const it = _2;
          const keyFrom = tableKey(it.from);
          return key.length + 3 + keyFrom.length;
        }).reduce((a, b) => {
          if (a > b) {
            return a;
          }
          return b;
        }, 0);
        const entityType = this.entityType;
        this.state.items.forEach((it, idx) => {
          const isSelected = idx === this.state.selectedIdx;
          const isRenamed = isRenamePromptItem(it);
          const title = isRenamed ? `${tableKey(it.from)} \u203A ${tableKey(it.to)}`.padEnd(labelLength, " ") : tableKey(it).padEnd(labelLength, " ");
          const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray(`rename ${entityType}`)}` : `${source_default.green("+")} ${title} ${source_default.gray(`create ${entityType}`)}`;
          text5 += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text5 += idx != this.state.items.length - 1 ? "\n" : "";
        });
        return text5;
      }
      result() {
        return this.state.items[this.state.selectedIdx];
      }
    };
    ResolveSchemasSelect = class extends import_hanji.Prompt {
      constructor(base, data) {
        super();
        this.base = base;
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.state = new import_hanji.SelectState(data);
        this.state.bind(this);
        this.base = base;
      }
      render(status) {
        if (status === "submitted" || status === "aborted") {
          return "";
        }
        let text5 = `
Is ${source_default.bold.blue(
          this.base.name
        )} schema created or renamed from another schema?
`;
        const isSelectedRenamed = isRenamePromptItem(
          this.state.items[this.state.selectedIdx]
        );
        const selectedPrefix = isSelectedRenamed ? source_default.yellow("\u276F ") : source_default.green("\u276F ");
        const labelLength = this.state.items.filter((it) => isRenamePromptItem(it)).map((it) => {
          return this.base.name.length + 3 + it["from"].name.length;
        }).reduce((a, b) => {
          if (a > b) {
            return a;
          }
          return b;
        }, 0);
        this.state.items.forEach((it, idx) => {
          const isSelected = idx === this.state.selectedIdx;
          const isRenamed = isRenamePromptItem(it);
          const title = isRenamed ? `${it.from.name} \u203A ${it.to.name}`.padEnd(labelLength, " ") : it.name.padEnd(labelLength, " ");
          const label = isRenamed ? `${source_default.yellow("~")} ${title} ${source_default.gray("rename schema")}` : `${source_default.green("+")} ${title} ${source_default.gray("create schema")}`;
          text5 += isSelected ? `${selectedPrefix}${label}` : `  ${label}`;
          text5 += idx != this.state.items.length - 1 ? "\n" : "";
        });
        return text5;
      }
      result() {
        return this.state.items[this.state.selectedIdx];
      }
    };
    Spinner = class {
      constructor(frames) {
        this.frames = frames;
        this.offset = 0;
        this.tick = () => {
          this.iterator();
        };
        this.value = () => {
          return this.frames[this.offset];
        };
        this.iterator = () => {
          this.offset += 1;
          this.offset %= frames.length - 1;
        };
      }
    };
    ProgressView = class extends import_hanji.TaskView {
      constructor(progressText, successText) {
        super();
        this.progressText = progressText;
        this.successText = successText;
        this.spinner = new Spinner("\u28F7\u28EF\u28DF\u287F\u28BF\u28FB\u28FD\u28FE".split(""));
        this.timeout = setInterval(() => {
          this.spinner.tick();
          this.requestLayout();
        }, 128);
        this.on("detach", () => clearInterval(this.timeout));
      }
      render(status) {
        if (status === "pending") {
          const spin = this.spinner.value();
          return `[${spin}] ${this.progressText}
`;
        }
        return `[${source_default.green("\u2713")}] ${this.successText}
`;
      }
    };
  }
});

// src/serializer/index.ts
var glob;
var init_serializer = __esm({
  "src/serializer/index.ts"() {
    "use strict";
    glob = __toESM(require_glob());
    init_views();
  }
});

// src/migrationPreparator.ts
var fillPgSnapshot;
var init_migrationPreparator = __esm({
  "src/migrationPreparator.ts"() {
    "use strict";
    init_serializer();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    fillPgSnapshot = ({
      serialized,
      id,
      idPrev
    }) => {
      return { id, prevId: idPrev, ...serialized };
    };
  }
});

// ../node_modules/.pnpm/heap@0.2.7/node_modules/heap/lib/heap.js
var require_heap = __commonJS({
  "../node_modules/.pnpm/heap@0.2.7/node_modules/heap/lib/heap.js"(exports, module) {
    "use strict";
    (function() {
      var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min2, nlargest, nsmallest, updateItem, _siftdown, _siftup;
      floor = Math.floor, min2 = Math.min;
      defaultCmp = function(x, y) {
        if (x < y) {
          return -1;
        }
        if (x > y) {
          return 1;
        }
        return 0;
      };
      insort = function(a, x, lo, hi, cmp) {
        var mid;
        if (lo == null) {
          lo = 0;
        }
        if (cmp == null) {
          cmp = defaultCmp;
        }
        if (lo < 0) {
          throw new Error("lo must be non-negative");
        }
        if (hi == null) {
          hi = a.length;
        }
        while (lo < hi) {
          mid = floor((lo + hi) / 2);
          if (cmp(x, a[mid]) < 0) {
            hi = mid;
          } else {
            lo = mid + 1;
          }
        }
        return [].splice.apply(a, [lo, lo - lo].concat(x)), x;
      };
      heappush = function(array2, item, cmp) {
        if (cmp == null) {
          cmp = defaultCmp;
        }
        array2.push(item);
        return _siftdown(array2, 0, array2.length - 1, cmp);
      };
      heappop = function(array2, cmp) {
        var lastelt, returnitem;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        lastelt = array2.pop();
        if (array2.length) {
          returnitem = array2[0];
          array2[0] = lastelt;
          _siftup(array2, 0, cmp);
        } else {
          returnitem = lastelt;
        }
        return returnitem;
      };
      heapreplace = function(array2, item, cmp) {
        var returnitem;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        returnitem = array2[0];
        array2[0] = item;
        _siftup(array2, 0, cmp);
        return returnitem;
      };
      heappushpop = function(array2, item, cmp) {
        var _ref;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        if (array2.length && cmp(array2[0], item) < 0) {
          _ref = [array2[0], item], item = _ref[0], array2[0] = _ref[1];
          _siftup(array2, 0, cmp);
        }
        return item;
      };
      heapify = function(array2, cmp) {
        var i, _i2, _j2, _len, _ref, _ref1, _results, _results1;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        _ref1 = function() {
          _results1 = [];
          for (var _j3 = 0, _ref2 = floor(array2.length / 2); 0 <= _ref2 ? _j3 < _ref2 : _j3 > _ref2; 0 <= _ref2 ? _j3++ : _j3--) {
            _results1.push(_j3);
          }
          return _results1;
        }.apply(this).reverse();
        _results = [];
        for (_i2 = 0, _len = _ref1.length; _i2 < _len; _i2++) {
          i = _ref1[_i2];
          _results.push(_siftup(array2, i, cmp));
        }
        return _results;
      };
      updateItem = function(array2, item, cmp) {
        var pos;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        pos = array2.indexOf(item);
        if (pos === -1) {
          return;
        }
        _siftdown(array2, 0, pos, cmp);
        return _siftup(array2, pos, cmp);
      };
      nlargest = function(array2, n, cmp) {
        var elem, result, _i2, _len, _ref;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        result = array2.slice(0, n);
        if (!result.length) {
          return result;
        }
        heapify(result, cmp);
        _ref = array2.slice(n);
        for (_i2 = 0, _len = _ref.length; _i2 < _len; _i2++) {
          elem = _ref[_i2];
          heappushpop(result, elem, cmp);
        }
        return result.sort(cmp).reverse();
      };
      nsmallest = function(array2, n, cmp) {
        var elem, i, los, result, _i2, _j2, _len, _ref, _ref1, _results;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        if (n * 10 <= array2.length) {
          result = array2.slice(0, n).sort(cmp);
          if (!result.length) {
            return result;
          }
          los = result[result.length - 1];
          _ref = array2.slice(n);
          for (_i2 = 0, _len = _ref.length; _i2 < _len; _i2++) {
            elem = _ref[_i2];
            if (cmp(elem, los) < 0) {
              insort(result, elem, 0, null, cmp);
              result.pop();
              los = result[result.length - 1];
            }
          }
          return result;
        }
        heapify(array2, cmp);
        _results = [];
        for (i = _j2 = 0, _ref1 = min2(n, array2.length); 0 <= _ref1 ? _j2 < _ref1 : _j2 > _ref1; i = 0 <= _ref1 ? ++_j2 : --_j2) {
          _results.push(heappop(array2, cmp));
        }
        return _results;
      };
      _siftdown = function(array2, startpos, pos, cmp) {
        var newitem, parent, parentpos;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        newitem = array2[pos];
        while (pos > startpos) {
          parentpos = pos - 1 >> 1;
          parent = array2[parentpos];
          if (cmp(newitem, parent) < 0) {
            array2[pos] = parent;
            pos = parentpos;
            continue;
          }
          break;
        }
        return array2[pos] = newitem;
      };
      _siftup = function(array2, pos, cmp) {
        var childpos, endpos, newitem, rightpos, startpos;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        endpos = array2.length;
        startpos = pos;
        newitem = array2[pos];
        childpos = 2 * pos + 1;
        while (childpos < endpos) {
          rightpos = childpos + 1;
          if (rightpos < endpos && !(cmp(array2[childpos], array2[rightpos]) < 0)) {
            childpos = rightpos;
          }
          array2[pos] = array2[childpos];
          pos = childpos;
          childpos = 2 * pos + 1;
        }
        array2[pos] = newitem;
        return _siftdown(array2, startpos, pos, cmp);
      };
      Heap = function() {
        Heap2.push = heappush;
        Heap2.pop = heappop;
        Heap2.replace = heapreplace;
        Heap2.pushpop = heappushpop;
        Heap2.heapify = heapify;
        Heap2.updateItem = updateItem;
        Heap2.nlargest = nlargest;
        Heap2.nsmallest = nsmallest;
        function Heap2(cmp) {
          this.cmp = cmp != null ? cmp : defaultCmp;
          this.nodes = [];
        }
        Heap2.prototype.push = function(x) {
          return heappush(this.nodes, x, this.cmp);
        };
        Heap2.prototype.pop = function() {
          return heappop(this.nodes, this.cmp);
        };
        Heap2.prototype.peek = function() {
          return this.nodes[0];
        };
        Heap2.prototype.contains = function(x) {
          return this.nodes.indexOf(x) !== -1;
        };
        Heap2.prototype.replace = function(x) {
          return heapreplace(this.nodes, x, this.cmp);
        };
        Heap2.prototype.pushpop = function(x) {
          return heappushpop(this.nodes, x, this.cmp);
        };
        Heap2.prototype.heapify = function() {
          return heapify(this.nodes, this.cmp);
        };
        Heap2.prototype.updateItem = function(x) {
          return updateItem(this.nodes, x, this.cmp);
        };
        Heap2.prototype.clear = function() {
          return this.nodes = [];
        };
        Heap2.prototype.empty = function() {
          return this.nodes.length === 0;
        };
        Heap2.prototype.size = function() {
          return this.nodes.length;
        };
        Heap2.prototype.clone = function() {
          var heap;
          heap = new Heap2();
          heap.nodes = this.nodes.slice(0);
          return heap;
        };
        Heap2.prototype.toArray = function() {
          return this.nodes.slice(0);
        };
        Heap2.prototype.insert = Heap2.prototype.push;
        Heap2.prototype.top = Heap2.prototype.peek;
        Heap2.prototype.front = Heap2.prototype.peek;
        Heap2.prototype.has = Heap2.prototype.contains;
        Heap2.prototype.copy = Heap2.prototype.clone;
        return Heap2;
      }();
      (function(root, factory) {
        if (typeof define === "function" && define.amd) {
          return define([], factory);
        } else if (typeof exports === "object") {
          return module.exports = factory();
        } else {
          return root.Heap = factory();
        }
      })(this, function() {
        return Heap;
      });
    }).call(exports);
  }
});

// ../node_modules/.pnpm/heap@0.2.7/node_modules/heap/index.js
var require_heap2 = __commonJS({
  "../node_modules/.pnpm/heap@0.2.7/node_modules/heap/index.js"(exports, module) {
    "use strict";
    module.exports = require_heap();
  }
});

// ../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/lib/difflib.js
var require_difflib = __commonJS({
  "../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/lib/difflib.js"(exports) {
    "use strict";
    (function() {
      var Differ, Heap, IS_CHARACTER_JUNK, IS_LINE_JUNK, SequenceMatcher, _any, _arrayCmp, _calculateRatio, _countLeading, _formatRangeContext, _formatRangeUnified, _has, assert, contextDiff, floor, getCloseMatches, max2, min2, ndiff, restore, unifiedDiff, indexOf = [].indexOf;
      ({ floor, max: max2, min: min2 } = Math);
      Heap = require_heap2();
      assert = __require("assert");
      _calculateRatio = function(matches, length) {
        if (length) {
          return 2 * matches / length;
        } else {
          return 1;
        }
      };
      _arrayCmp = function(a, b) {
        var i, l, la, lb, ref;
        [la, lb] = [a.length, b.length];
        for (i = l = 0, ref = min2(la, lb); 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {
          if (a[i] < b[i]) {
            return -1;
          }
          if (a[i] > b[i]) {
            return 1;
          }
        }
        return la - lb;
      };
      _has = function(obj, key) {
        return Object.prototype.hasOwnProperty.call(obj, key);
      };
      _any = function(items) {
        var item, l, len;
        for (l = 0, len = items.length; l < len; l++) {
          item = items[l];
          if (item) {
            return true;
          }
        }
        return false;
      };
      SequenceMatcher = class SequenceMatcher {
        /*
            SequenceMatcher is a flexible class for comparing pairs of sequences of
            any type, so long as the sequence elements are hashable.  The basic
            algorithm predates, and is a little fancier than, an algorithm
            published in the late 1980's by Ratcliff and Obershelp under the
            hyperbolic name "gestalt pattern matching".  The basic idea is to find
            the longest contiguous matching subsequence that contains no "junk"
            elements (R-O doesn't address junk).  The same idea is then applied
            recursively to the pieces of the sequences to the left and to the right
            of the matching subsequence.  This does not yield minimal edit
            sequences, but does tend to yield matches that "look right" to people.
        
            SequenceMatcher tries to compute a "human-friendly diff" between two
            sequences.  Unlike e.g. UNIX(tm) diff, the fundamental notion is the
            longest *contiguous* & junk-free matching subsequence.  That's what
            catches peoples' eyes.  The Windows(tm) windiff has another interesting
            notion, pairing up elements that appear uniquely in each sequence.
            That, and the method here, appear to yield more intuitive difference
            reports than does diff.  This method appears to be the least vulnerable
            to synching up on blocks of "junk lines", though (like blank lines in
            ordinary text files, or maybe "<P>" lines in HTML files).  That may be
            because this is the only method of the 3 that has a *concept* of
            "junk" <wink>.
        
            Example, comparing two strings, and considering blanks to be "junk":
        
            >>> isjunk = (c) -> c is ' '
            >>> s = new SequenceMatcher(isjunk,
                                        'private Thread currentThread;',
                                        'private volatile Thread currentThread;')
        
            .ratio() returns a float in [0, 1], measuring the "similarity" of the
            sequences.  As a rule of thumb, a .ratio() value over 0.6 means the
            sequences are close matches:
        
            >>> s.ratio().toPrecision(3)
            '0.866'
        
            If you're only interested in where the sequences match,
            .getMatchingBlocks() is handy:
        
            >>> for [a, b, size] in s.getMatchingBlocks()
            ...   console.log("a[#{a}] and b[#{b}] match for #{size} elements");
            a[0] and b[0] match for 8 elements
            a[8] and b[17] match for 21 elements
            a[29] and b[38] match for 0 elements
        
            Note that the last tuple returned by .get_matching_blocks() is always a
            dummy, (len(a), len(b), 0), and this is the only case in which the last
            tuple element (number of elements matched) is 0.
        
            If you want to know how to change the first sequence into the second,
            use .get_opcodes():
        
            >>> for [op, a1, a2, b1, b2] in s.getOpcodes()
            ...   console.log "#{op} a[#{a1}:#{a2}] b[#{b1}:#{b2}]"
            equal a[0:8] b[0:8]
            insert a[8:8] b[8:17]
            equal a[8:29] b[17:38]
        
            See the Differ class for a fancy human-friendly file differencer, which
            uses SequenceMatcher both to compare sequences of lines, and to compare
            sequences of characters within similar (near-matching) lines.
        
            See also function getCloseMatches() in this module, which shows how
            simple code building on SequenceMatcher can be used to do useful work.
        
            Timing:  Basic R-O is cubic time worst case and quadratic time expected
            case.  SequenceMatcher is quadratic time for the worst case and has
            expected-case behavior dependent in a complicated way on how many
            elements the sequences have in common; best case time is linear.
        
            Methods:
        
            constructor(isjunk=null, a='', b='')
                Construct a SequenceMatcher.
        
            setSeqs(a, b)
                Set the two sequences to be compared.
        
            setSeq1(a)
                Set the first sequence to be compared.
        
            setSeq2(b)
                Set the second sequence to be compared.
        
            findLongestMatch(alo, ahi, blo, bhi)
                Find longest matching block in a[alo:ahi] and b[blo:bhi].
        
            getMatchingBlocks()
                Return list of triples describing matching subsequences.
        
            getOpcodes()
                Return list of 5-tuples describing how to turn a into b.
        
            ratio()
                Return a measure of the sequences' similarity (float in [0,1]).
        
            quickRatio()
                Return an upper bound on .ratio() relatively quickly.
        
            realQuickRatio()
                Return an upper bound on ratio() very quickly.
            */
        constructor(isjunk1, a = "", b = "", autojunk = true) {
          this.isjunk = isjunk1;
          this.autojunk = autojunk;
          this.a = this.b = null;
          this.setSeqs(a, b);
        }
        setSeqs(a, b) {
          this.setSeq1(a);
          return this.setSeq2(b);
        }
        setSeq1(a) {
          if (a === this.a) {
            return;
          }
          this.a = a;
          return this.matchingBlocks = this.opcodes = null;
        }
        setSeq2(b) {
          if (b === this.b) {
            return;
          }
          this.b = b;
          this.matchingBlocks = this.opcodes = null;
          this.fullbcount = null;
          return this._chainB();
        }
        // For each element x in b, set b2j[x] to a list of the indices in
        // b where x appears; the indices are in increasing order; note that
        // the number of times x appears in b is b2j[x].length ...
        // when @isjunk is defined, junk elements don't show up in this
        // map at all, which stops the central findLongestMatch method
        // from starting any matching block at a junk element ...
        // also creates the fast isbjunk function ...
        // b2j also does not contain entries for "popular" elements, meaning
        // elements that account for more than 1 + 1% of the total elements, and
        // when the sequence is reasonably large (>= 200 elements); this can
        // be viewed as an adaptive notion of semi-junk, and yields an enormous
        // speedup when, e.g., comparing program files with hundreds of
        // instances of "return null;" ...
        // note that this is only called when b changes; so for cross-product
        // kinds of matches, it's best to call setSeq2 once, then setSeq1
        // repeatedly
        _chainB() {
          var b, b2j, elt, i, indices, isjunk, junk, l, len, n, ntest, popular;
          b = this.b;
          this.b2j = b2j = /* @__PURE__ */ new Map();
          for (i = l = 0, len = b.length; l < len; i = ++l) {
            elt = b[i];
            if (!b2j.has(elt)) {
              b2j.set(elt, []);
            }
            indices = b2j.get(elt);
            indices.push(i);
          }
          junk = /* @__PURE__ */ new Map();
          isjunk = this.isjunk;
          if (isjunk) {
            b2j.forEach(function(idxs, elt2) {
              if (isjunk(elt2)) {
                junk.set(elt2, true);
                return b2j.delete(elt2);
              }
            });
          }
          popular = /* @__PURE__ */ new Map();
          n = b.length;
          if (this.autojunk && n >= 200) {
            ntest = floor(n / 100) + 1;
            b2j.forEach(function(idxs, elt2) {
              if (idxs.length > ntest) {
                popular.set(elt2, true);
                return b2j.delete(elt2);
              }
            });
          }
          this.isbjunk = function(b2) {
            return junk.has(b2);
          };
          return this.isbpopular = function(b2) {
            return popular.has(b2);
          };
        }
        findLongestMatch(alo, ahi, blo, bhi) {
          var a, b, b2j, besti, bestj, bestsize, i, isbjunk, j, j2len, jlist, k, l, len, m, newj2len, ref, ref1;
          [a, b, b2j, isbjunk] = [this.a, this.b, this.b2j, this.isbjunk];
          [besti, bestj, bestsize] = [alo, blo, 0];
          j2len = {};
          for (i = l = ref = alo, ref1 = ahi; ref <= ref1 ? l < ref1 : l > ref1; i = ref <= ref1 ? ++l : --l) {
            newj2len = {};
            jlist = [];
            if (b2j.has(a[i])) {
              jlist = b2j.get(a[i]);
            }
            for (m = 0, len = jlist.length; m < len; m++) {
              j = jlist[m];
              if (j < blo) {
                continue;
              }
              if (j >= bhi) {
                break;
              }
              k = newj2len[j] = (j2len[j - 1] || 0) + 1;
              if (k > bestsize) {
                [besti, bestj, bestsize] = [i - k + 1, j - k + 1, k];
              }
            }
            j2len = newj2len;
          }
          while (besti > alo && bestj > blo && !isbjunk(b[bestj - 1]) && a[besti - 1] === b[bestj - 1]) {
            [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1];
          }
          while (besti + bestsize < ahi && bestj + bestsize < bhi && !isbjunk(b[bestj + bestsize]) && a[besti + bestsize] === b[bestj + bestsize]) {
            bestsize++;
          }
          while (besti > alo && bestj > blo && isbjunk(b[bestj - 1]) && a[besti - 1] === b[bestj - 1]) {
            [besti, bestj, bestsize] = [besti - 1, bestj - 1, bestsize + 1];
          }
          while (besti + bestsize < ahi && bestj + bestsize < bhi && isbjunk(b[bestj + bestsize]) && a[besti + bestsize] === b[bestj + bestsize]) {
            bestsize++;
          }
          return [besti, bestj, bestsize];
        }
        getMatchingBlocks() {
          var ahi, alo, bhi, blo, i, i1, i2, j, j1, j2, k, k1, k2, l, la, lb, len, matchingBlocks, nonAdjacent, queue, x;
          if (this.matchingBlocks) {
            return this.matchingBlocks;
          }
          [la, lb] = [this.a.length, this.b.length];
          queue = [[0, la, 0, lb]];
          matchingBlocks = [];
          while (queue.length) {
            [alo, ahi, blo, bhi] = queue.pop();
            [i, j, k] = x = this.findLongestMatch(alo, ahi, blo, bhi);
            if (k) {
              matchingBlocks.push(x);
              if (alo < i && blo < j) {
                queue.push([alo, i, blo, j]);
              }
              if (i + k < ahi && j + k < bhi) {
                queue.push([i + k, ahi, j + k, bhi]);
              }
            }
          }
          matchingBlocks.sort(_arrayCmp);
          i1 = j1 = k1 = 0;
          nonAdjacent = [];
          for (l = 0, len = matchingBlocks.length; l < len; l++) {
            [i2, j2, k2] = matchingBlocks[l];
            if (i1 + k1 === i2 && j1 + k1 === j2) {
              k1 += k2;
            } else {
              if (k1) {
                nonAdjacent.push([i1, j1, k1]);
              }
              [i1, j1, k1] = [i2, j2, k2];
            }
          }
          if (k1) {
            nonAdjacent.push([i1, j1, k1]);
          }
          nonAdjacent.push([la, lb, 0]);
          return this.matchingBlocks = nonAdjacent;
        }
        getOpcodes() {
          var ai, answer, bj, i, j, l, len, ref, size, tag;
          if (this.opcodes) {
            return this.opcodes;
          }
          i = j = 0;
          this.opcodes = answer = [];
          ref = this.getMatchingBlocks();
          for (l = 0, len = ref.length; l < len; l++) {
            [ai, bj, size] = ref[l];
            tag = "";
            if (i < ai && j < bj) {
              tag = "replace";
            } else if (i < ai) {
              tag = "delete";
            } else if (j < bj) {
              tag = "insert";
            }
            if (tag) {
              answer.push([tag, i, ai, j, bj]);
            }
            [i, j] = [ai + size, bj + size];
            if (size) {
              answer.push(["equal", ai, i, bj, j]);
            }
          }
          return answer;
        }
        getGroupedOpcodes(n = 3) {
          var codes, group, groups, i1, i2, j1, j2, l, len, nn, tag;
          codes = this.getOpcodes();
          if (!codes.length) {
            codes = [["equal", 0, 1, 0, 1]];
          }
          if (codes[0][0] === "equal") {
            [tag, i1, i2, j1, j2] = codes[0];
            codes[0] = [tag, max2(i1, i2 - n), i2, max2(j1, j2 - n), j2];
          }
          if (codes[codes.length - 1][0] === "equal") {
            [tag, i1, i2, j1, j2] = codes[codes.length - 1];
            codes[codes.length - 1] = [tag, i1, min2(i2, i1 + n), j1, min2(j2, j1 + n)];
          }
          nn = n + n;
          groups = [];
          group = [];
          for (l = 0, len = codes.length; l < len; l++) {
            [tag, i1, i2, j1, j2] = codes[l];
            if (tag === "equal" && i2 - i1 > nn) {
              group.push([tag, i1, min2(i2, i1 + n), j1, min2(j2, j1 + n)]);
              groups.push(group);
              group = [];
              [i1, j1] = [max2(i1, i2 - n), max2(j1, j2 - n)];
            }
            group.push([tag, i1, i2, j1, j2]);
          }
          if (group.length && !(group.length === 1 && group[0][0] === "equal")) {
            groups.push(group);
          }
          return groups;
        }
        ratio() {
          var l, len, match2, matches, ref;
          matches = 0;
          ref = this.getMatchingBlocks();
          for (l = 0, len = ref.length; l < len; l++) {
            match2 = ref[l];
            matches += match2[2];
          }
          return _calculateRatio(matches, this.a.length + this.b.length);
        }
        quickRatio() {
          var avail, elt, fullbcount, l, len, len1, m, matches, numb, ref, ref1;
          if (!this.fullbcount) {
            this.fullbcount = fullbcount = {};
            ref = this.b;
            for (l = 0, len = ref.length; l < len; l++) {
              elt = ref[l];
              fullbcount[elt] = (fullbcount[elt] || 0) + 1;
            }
          }
          fullbcount = this.fullbcount;
          avail = {};
          matches = 0;
          ref1 = this.a;
          for (m = 0, len1 = ref1.length; m < len1; m++) {
            elt = ref1[m];
            if (_has(avail, elt)) {
              numb = avail[elt];
            } else {
              numb = fullbcount[elt] || 0;
            }
            avail[elt] = numb - 1;
            if (numb > 0) {
              matches++;
            }
          }
          return _calculateRatio(matches, this.a.length + this.b.length);
        }
        realQuickRatio() {
          var la, lb;
          [la, lb] = [this.a.length, this.b.length];
          return _calculateRatio(min2(la, lb), la + lb);
        }
      };
      getCloseMatches = function(word, possibilities, n = 3, cutoff = 0.6) {
        var l, len, len1, m, result, results, s, score, x;
        if (!(n > 0)) {
          throw new Error(`n must be > 0: (${n})`);
        }
        if (!(0 <= cutoff && cutoff <= 1)) {
          throw new Error(`cutoff must be in [0.0, 1.0]: (${cutoff})`);
        }
        result = [];
        s = new SequenceMatcher();
        s.setSeq2(word);
        for (l = 0, len = possibilities.length; l < len; l++) {
          x = possibilities[l];
          s.setSeq1(x);
          if (s.realQuickRatio() >= cutoff && s.quickRatio() >= cutoff && s.ratio() >= cutoff) {
            result.push([s.ratio(), x]);
          }
        }
        result = Heap.nlargest(result, n, _arrayCmp);
        results = [];
        for (m = 0, len1 = result.length; m < len1; m++) {
          [score, x] = result[m];
          results.push(x);
        }
        return results;
      };
      _countLeading = function(line2, ch) {
        var i, n;
        [i, n] = [0, line2.length];
        while (i < n && line2[i] === ch) {
          i++;
        }
        return i;
      };
      Differ = class Differ {
        /*
            Differ is a class for comparing sequences of lines of text, and
            producing human-readable differences or deltas.  Differ uses
            SequenceMatcher both to compare sequences of lines, and to compare
            sequences of characters within similar (near-matching) lines.
        
            Each line of a Differ delta begins with a two-letter code:
        
                '- '    line unique to sequence 1
                '+ '    line unique to sequence 2
                '  '    line common to both sequences
                '? '    line not present in either input sequence
        
            Lines beginning with '? ' attempt to guide the eye to intraline
            differences, and were not present in either input sequence.  These lines
            can be confusing if the sequences contain tab characters.
        
            Note that Differ makes no claim to produce a *minimal* diff.  To the
            contrary, minimal diffs are often counter-intuitive, because they synch
            up anywhere possible, sometimes accidental matches 100 pages apart.
            Restricting synch points to contiguous matches preserves some notion of
            locality, at the occasional cost of producing a longer diff.
        
            Example: Comparing two texts.
        
            >>> text1 = ['1. Beautiful is better than ugly.\n',
            ...   '2. Explicit is better than implicit.\n',
            ...   '3. Simple is better than complex.\n',
            ...   '4. Complex is better than complicated.\n']
            >>> text1.length
            4
            >>> text2 = ['1. Beautiful is better than ugly.\n',
            ...   '3.   Simple is better than complex.\n',
            ...   '4. Complicated is better than complex.\n',
            ...   '5. Flat is better than nested.\n']
        
            Next we instantiate a Differ object:
        
            >>> d = new Differ()
        
            Note that when instantiating a Differ object we may pass functions to
            filter out line and character 'junk'.
        
            Finally, we compare the two:
        
            >>> result = d.compare(text1, text2)
            [ '  1. Beautiful is better than ugly.\n',
              '- 2. Explicit is better than implicit.\n',
              '- 3. Simple is better than complex.\n',
              '+ 3.   Simple is better than complex.\n',
              '?   ++\n',
              '- 4. Complex is better than complicated.\n',
              '?          ^                     ---- ^\n',
              '+ 4. Complicated is better than complex.\n',
              '?         ++++ ^                      ^\n',
              '+ 5. Flat is better than nested.\n' ]
        
            Methods:
        
            constructor(linejunk=null, charjunk=null)
                Construct a text differencer, with optional filters.
            compare(a, b)
                Compare two sequences of lines; generate the resulting delta.
            */
        constructor(linejunk1, charjunk1) {
          this.linejunk = linejunk1;
          this.charjunk = charjunk1;
        }
        /*
            Construct a text differencer, with optional filters.
        
            The two optional keyword parameters are for filter functions:
        
            - `linejunk`: A function that should accept a single string argument,
              and return true iff the string is junk. The module-level function
              `IS_LINE_JUNK` may be used to filter out lines without visible
              characters, except for at most one splat ('#').  It is recommended
              to leave linejunk null. 
        
            - `charjunk`: A function that should accept a string of length 1. The
              module-level function `IS_CHARACTER_JUNK` may be used to filter out
              whitespace characters (a blank or tab; **note**: bad idea to include
              newline in this!).  Use of IS_CHARACTER_JUNK is recommended.
            */
        compare(a, b) {
          var ahi, alo, bhi, blo, cruncher, g, l, len, len1, line2, lines, m, ref, tag;
          cruncher = new SequenceMatcher(this.linejunk, a, b);
          lines = [];
          ref = cruncher.getOpcodes();
          for (l = 0, len = ref.length; l < len; l++) {
            [tag, alo, ahi, blo, bhi] = ref[l];
            switch (tag) {
              case "replace":
                g = this._fancyReplace(a, alo, ahi, b, blo, bhi);
                break;
              case "delete":
                g = this._dump("-", a, alo, ahi);
                break;
              case "insert":
                g = this._dump("+", b, blo, bhi);
                break;
              case "equal":
                g = this._dump(" ", a, alo, ahi);
                break;
              default:
                throw new Error(`unknow tag (${tag})`);
            }
            for (m = 0, len1 = g.length; m < len1; m++) {
              line2 = g[m];
              lines.push(line2);
            }
          }
          return lines;
        }
        _dump(tag, x, lo, hi) {
          var i, l, ref, ref1, results;
          results = [];
          for (i = l = ref = lo, ref1 = hi; ref <= ref1 ? l < ref1 : l > ref1; i = ref <= ref1 ? ++l : --l) {
            results.push(`${tag} ${x[i]}`);
          }
          return results;
        }
        _plainReplace(a, alo, ahi, b, blo, bhi) {
          var first, g, l, len, len1, line2, lines, m, ref, second;
          assert(alo < ahi && blo < bhi);
          if (bhi - blo < ahi - alo) {
            first = this._dump("+", b, blo, bhi);
            second = this._dump("-", a, alo, ahi);
          } else {
            first = this._dump("-", a, alo, ahi);
            second = this._dump("+", b, blo, bhi);
          }
          lines = [];
          ref = [first, second];
          for (l = 0, len = ref.length; l < len; l++) {
            g = ref[l];
            for (m = 0, len1 = g.length; m < len1; m++) {
              line2 = g[m];
              lines.push(line2);
            }
          }
          return lines;
        }
        _fancyReplace(a, alo, ahi, b, blo, bhi) {
          var aelt, ai, ai1, ai2, atags, belt, bestRatio, besti, bestj, bj, bj1, bj2, btags, cruncher, cutoff, eqi, eqj, i, j, l, la, lb, len, len1, len2, len3, len4, line2, lines, m, o, p, q, r, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, t, tag;
          [bestRatio, cutoff] = [0.74, 0.75];
          cruncher = new SequenceMatcher(this.charjunk);
          [eqi, eqj] = [
            null,
            null
            // 1st indices of equal lines (if any)
          ];
          lines = [];
          for (j = l = ref = blo, ref1 = bhi; ref <= ref1 ? l < ref1 : l > ref1; j = ref <= ref1 ? ++l : --l) {
            bj = b[j];
            cruncher.setSeq2(bj);
            for (i = m = ref2 = alo, ref3 = ahi; ref2 <= ref3 ? m < ref3 : m > ref3; i = ref2 <= ref3 ? ++m : --m) {
              ai = a[i];
              if (ai === bj) {
                if (eqi === null) {
                  [eqi, eqj] = [i, j];
                }
                continue;
              }
              cruncher.setSeq1(ai);
              if (cruncher.realQuickRatio() > bestRatio && cruncher.quickRatio() > bestRatio && cruncher.ratio() > bestRatio) {
                [bestRatio, besti, bestj] = [cruncher.ratio(), i, j];
              }
            }
          }
          if (bestRatio < cutoff) {
            if (eqi === null) {
              ref4 = this._plainReplace(a, alo, ahi, b, blo, bhi);
              for (o = 0, len = ref4.length; o < len; o++) {
                line2 = ref4[o];
                lines.push(line2);
              }
              return lines;
            }
            [besti, bestj, bestRatio] = [eqi, eqj, 1];
          } else {
            eqi = null;
          }
          ref5 = this._fancyHelper(a, alo, besti, b, blo, bestj);
          for (p = 0, len1 = ref5.length; p < len1; p++) {
            line2 = ref5[p];
            lines.push(line2);
          }
          [aelt, belt] = [a[besti], b[bestj]];
          if (eqi === null) {
            atags = btags = "";
            cruncher.setSeqs(aelt, belt);
            ref6 = cruncher.getOpcodes();
            for (q = 0, len2 = ref6.length; q < len2; q++) {
              [tag, ai1, ai2, bj1, bj2] = ref6[q];
              [la, lb] = [ai2 - ai1, bj2 - bj1];
              switch (tag) {
                case "replace":
                  atags += Array(la + 1).join("^");
                  btags += Array(lb + 1).join("^");
                  break;
                case "delete":
                  atags += Array(la + 1).join("-");
                  break;
                case "insert":
                  btags += Array(lb + 1).join("+");
                  break;
                case "equal":
                  atags += Array(la + 1).join(" ");
                  btags += Array(lb + 1).join(" ");
                  break;
                default:
                  throw new Error(`unknow tag (${tag})`);
              }
            }
            ref7 = this._qformat(aelt, belt, atags, btags);
            for (r = 0, len3 = ref7.length; r < len3; r++) {
              line2 = ref7[r];
              lines.push(line2);
            }
          } else {
            lines.push("  " + aelt);
          }
          ref8 = this._fancyHelper(a, besti + 1, ahi, b, bestj + 1, bhi);
          for (t = 0, len4 = ref8.length; t < len4; t++) {
            line2 = ref8[t];
            lines.push(line2);
          }
          return lines;
        }
        _fancyHelper(a, alo, ahi, b, blo, bhi) {
          var g;
          g = [];
          if (alo < ahi) {
            if (blo < bhi) {
              g = this._fancyReplace(a, alo, ahi, b, blo, bhi);
            } else {
              g = this._dump("-", a, alo, ahi);
            }
          } else if (blo < bhi) {
            g = this._dump("+", b, blo, bhi);
          }
          return g;
        }
        _qformat(aline, bline, atags, btags) {
          var common, lines;
          lines = [];
          common = min2(_countLeading(aline, "	"), _countLeading(bline, "	"));
          common = min2(common, _countLeading(atags.slice(0, common), " "));
          common = min2(common, _countLeading(btags.slice(0, common), " "));
          atags = atags.slice(common).replace(/\s+$/, "");
          btags = btags.slice(common).replace(/\s+$/, "");
          lines.push("- " + aline);
          if (atags.length) {
            lines.push(`? ${Array(common + 1).join("	")}${atags}
`);
          }
          lines.push("+ " + bline);
          if (btags.length) {
            lines.push(`? ${Array(common + 1).join("	")}${btags}
`);
          }
          return lines;
        }
      };
      IS_LINE_JUNK = function(line2, pat = /^\s*#?\s*$/) {
        return pat.test(line2);
      };
      IS_CHARACTER_JUNK = function(ch, ws = " 	") {
        return indexOf.call(ws, ch) >= 0;
      };
      _formatRangeUnified = function(start, stop) {
        var beginning, length;
        beginning = start + 1;
        length = stop - start;
        if (length === 1) {
          return `${beginning}`;
        }
        if (!length) {
          beginning--;
        }
        return `${beginning},${length}`;
      };
      unifiedDiff = function(a, b, { fromfile, tofile, fromfiledate, tofiledate, n, lineterm } = {}) {
        var file1Range, file2Range, first, fromdate, group, i1, i2, j1, j2, l, last, len, len1, len2, len3, len4, line2, lines, m, o, p, q, ref, ref1, ref2, ref3, started, tag, todate;
        if (fromfile == null) {
          fromfile = "";
        }
        if (tofile == null) {
          tofile = "";
        }
        if (fromfiledate == null) {
          fromfiledate = "";
        }
        if (tofiledate == null) {
          tofiledate = "";
        }
        if (n == null) {
          n = 3;
        }
        if (lineterm == null) {
          lineterm = "\n";
        }
        lines = [];
        started = false;
        ref = new SequenceMatcher(null, a, b).getGroupedOpcodes();
        for (l = 0, len = ref.length; l < len; l++) {
          group = ref[l];
          if (!started) {
            started = true;
            fromdate = fromfiledate ? `	${fromfiledate}` : "";
            todate = tofiledate ? `	${tofiledate}` : "";
            lines.push(`--- ${fromfile}${fromdate}${lineterm}`);
            lines.push(`+++ ${tofile}${todate}${lineterm}`);
          }
          [first, last] = [group[0], group[group.length - 1]];
          file1Range = _formatRangeUnified(first[1], last[2]);
          file2Range = _formatRangeUnified(first[3], last[4]);
          lines.push(`@@ -${file1Range} +${file2Range} @@${lineterm}`);
          for (m = 0, len1 = group.length; m < len1; m++) {
            [tag, i1, i2, j1, j2] = group[m];
            if (tag === "equal") {
              ref1 = a.slice(i1, i2);
              for (o = 0, len2 = ref1.length; o < len2; o++) {
                line2 = ref1[o];
                lines.push(" " + line2);
              }
              continue;
            }
            if (tag === "replace" || tag === "delete") {
              ref2 = a.slice(i1, i2);
              for (p = 0, len3 = ref2.length; p < len3; p++) {
                line2 = ref2[p];
                lines.push("-" + line2);
              }
            }
            if (tag === "replace" || tag === "insert") {
              ref3 = b.slice(j1, j2);
              for (q = 0, len4 = ref3.length; q < len4; q++) {
                line2 = ref3[q];
                lines.push("+" + line2);
              }
            }
          }
        }
        return lines;
      };
      _formatRangeContext = function(start, stop) {
        var beginning, length;
        beginning = start + 1;
        length = stop - start;
        if (!length) {
          beginning--;
        }
        if (length <= 1) {
          return `${beginning}`;
        }
        return `${beginning},${beginning + length - 1}`;
      };
      contextDiff = function(a, b, { fromfile, tofile, fromfiledate, tofiledate, n, lineterm } = {}) {
        var _2, file1Range, file2Range, first, fromdate, group, i1, i2, j1, j2, l, last, len, len1, len2, len3, len4, line2, lines, m, o, p, prefix2, q, ref, ref1, ref2, started, tag, todate;
        if (fromfile == null) {
          fromfile = "";
        }
        if (tofile == null) {
          tofile = "";
        }
        if (fromfiledate == null) {
          fromfiledate = "";
        }
        if (tofiledate == null) {
          tofiledate = "";
        }
        if (n == null) {
          n = 3;
        }
        if (lineterm == null) {
          lineterm = "\n";
        }
        prefix2 = {
          insert: "+ ",
          delete: "- ",
          replace: "! ",
          equal: "  "
        };
        started = false;
        lines = [];
        ref = new SequenceMatcher(null, a, b).getGroupedOpcodes();
        for (l = 0, len = ref.length; l < len; l++) {
          group = ref[l];
          if (!started) {
            started = true;
            fromdate = fromfiledate ? `	${fromfiledate}` : "";
            todate = tofiledate ? `	${tofiledate}` : "";
            lines.push(`*** ${fromfile}${fromdate}${lineterm}`);
            lines.push(`--- ${tofile}${todate}${lineterm}`);
            [first, last] = [group[0], group[group.length - 1]];
            lines.push("***************" + lineterm);
            file1Range = _formatRangeContext(first[1], last[2]);
            lines.push(`*** ${file1Range} ****${lineterm}`);
            if (_any(function() {
              var len12, m2, results;
              results = [];
              for (m2 = 0, len12 = group.length; m2 < len12; m2++) {
                [tag, _2, _2, _2, _2] = group[m2];
                results.push(tag === "replace" || tag === "delete");
              }
              return results;
            }())) {
              for (m = 0, len1 = group.length; m < len1; m++) {
                [tag, i1, i2, _2, _2] = group[m];
                if (tag !== "insert") {
                  ref1 = a.slice(i1, i2);
                  for (o = 0, len2 = ref1.length; o < len2; o++) {
                    line2 = ref1[o];
                    lines.push(prefix2[tag] + line2);
                  }
                }
              }
            }
            file2Range = _formatRangeContext(first[3], last[4]);
            lines.push(`--- ${file2Range} ----${lineterm}`);
            if (_any(function() {
              var len32, p2, results;
              results = [];
              for (p2 = 0, len32 = group.length; p2 < len32; p2++) {
                [tag, _2, _2, _2, _2] = group[p2];
                results.push(tag === "replace" || tag === "insert");
              }
              return results;
            }())) {
              for (p = 0, len3 = group.length; p < len3; p++) {
                [tag, _2, _2, j1, j2] = group[p];
                if (tag !== "delete") {
                  ref2 = b.slice(j1, j2);
                  for (q = 0, len4 = ref2.length; q < len4; q++) {
                    line2 = ref2[q];
                    lines.push(prefix2[tag] + line2);
                  }
                }
              }
            }
          }
        }
        return lines;
      };
      ndiff = function(a, b, linejunk, charjunk = IS_CHARACTER_JUNK) {
        return new Differ(linejunk, charjunk).compare(a, b);
      };
      restore = function(delta, which) {
        var l, len, line2, lines, prefixes2, ref, tag;
        tag = {
          1: "- ",
          2: "+ "
        }[which];
        if (!tag) {
          throw new Error(`unknow delta choice (must be 1 or 2): ${which}`);
        }
        prefixes2 = ["  ", tag];
        lines = [];
        for (l = 0, len = delta.length; l < len; l++) {
          line2 = delta[l];
          if (ref = line2.slice(0, 2), indexOf.call(prefixes2, ref) >= 0) {
            lines.push(line2.slice(2));
          }
        }
        return lines;
      };
      exports._arrayCmp = _arrayCmp;
      exports.SequenceMatcher = SequenceMatcher;
      exports.getCloseMatches = getCloseMatches;
      exports._countLeading = _countLeading;
      exports.Differ = Differ;
      exports.IS_LINE_JUNK = IS_LINE_JUNK;
      exports.IS_CHARACTER_JUNK = IS_CHARACTER_JUNK;
      exports._formatRangeUnified = _formatRangeUnified;
      exports.unifiedDiff = unifiedDiff;
      exports._formatRangeContext = _formatRangeContext;
      exports.contextDiff = contextDiff;
      exports.ndiff = ndiff;
      exports.restore = restore;
    }).call(exports);
  }
});

// ../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/index.js
var require_difflib2 = __commonJS({
  "../node_modules/.pnpm/@ewoudenberg+difflib@0.1.0/node_modules/@ewoudenberg/difflib/index.js"(exports, module) {
    "use strict";
    module.exports = require_difflib();
  }
});

// ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/util.js
var require_util = __commonJS({
  "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/util.js"(exports, module) {
    "use strict";
    var extendedTypeOf = function(obj) {
      const result = typeof obj;
      if (obj == null) {
        return "null";
      } else if (result === "object" && obj.constructor === Array) {
        return "array";
      } else if (result === "object" && obj instanceof Date) {
        return "date";
      } else {
        return result;
      }
    };
    var roundObj = function(data, precision) {
      const type = typeof data;
      if (type === "array") {
        return data.map((x) => roundObj(x, precision));
      } else if (type === "object") {
        for (const key in data) {
          data[key] = roundObj(data[key], precision);
        }
        return data;
      } else if (type === "number" && Number.isFinite(data) && !Number.isInteger(data)) {
        return +data.toFixed(precision);
      } else {
        return data;
      }
    };
    module.exports = { extendedTypeOf, roundObj };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/styles.js
var require_styles = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/styles.js"(exports, module) {
    "use strict";
    var styles3 = {};
    module["exports"] = styles3;
    var codes = {
      reset: [0, 0],
      bold: [1, 22],
      dim: [2, 22],
      italic: [3, 23],
      underline: [4, 24],
      inverse: [7, 27],
      hidden: [8, 28],
      strikethrough: [9, 29],
      black: [30, 39],
      red: [31, 39],
      green: [32, 39],
      yellow: [33, 39],
      blue: [34, 39],
      magenta: [35, 39],
      cyan: [36, 39],
      white: [37, 39],
      gray: [90, 39],
      grey: [90, 39],
      brightRed: [91, 39],
      brightGreen: [92, 39],
      brightYellow: [93, 39],
      brightBlue: [94, 39],
      brightMagenta: [95, 39],
      brightCyan: [96, 39],
      brightWhite: [97, 39],
      bgBlack: [40, 49],
      bgRed: [41, 49],
      bgGreen: [42, 49],
      bgYellow: [43, 49],
      bgBlue: [44, 49],
      bgMagenta: [45, 49],
      bgCyan: [46, 49],
      bgWhite: [47, 49],
      bgGray: [100, 49],
      bgGrey: [100, 49],
      bgBrightRed: [101, 49],
      bgBrightGreen: [102, 49],
      bgBrightYellow: [103, 49],
      bgBrightBlue: [104, 49],
      bgBrightMagenta: [105, 49],
      bgBrightCyan: [106, 49],
      bgBrightWhite: [107, 49],
      // legacy styles for colors pre v1.0.0
      blackBG: [40, 49],
      redBG: [41, 49],
      greenBG: [42, 49],
      yellowBG: [43, 49],
      blueBG: [44, 49],
      magentaBG: [45, 49],
      cyanBG: [46, 49],
      whiteBG: [47, 49]
    };
    Object.keys(codes).forEach(function(key) {
      var val = codes[key];
      var style = styles3[key] = [];
      style.open = "\x1B[" + val[0] + "m";
      style.close = "\x1B[" + val[1] + "m";
    });
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/has-flag.js
var require_has_flag = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/has-flag.js"(exports, module) {
    "use strict";
    module.exports = function(flag, argv) {
      argv = argv || process.argv;
      var terminatorPos = argv.indexOf("--");
      var prefix2 = /^-{1,2}/.test(flag) ? "" : "--";
      var pos = argv.indexOf(prefix2 + flag);
      return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/supports-colors.js
var require_supports_colors = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/system/supports-colors.js"(exports, module) {
    "use strict";
    var os2 = __require("os");
    var hasFlag2 = require_has_flag();
    var env2 = process.env;
    var forceColor = void 0;
    if (hasFlag2("no-color") || hasFlag2("no-colors") || hasFlag2("color=false")) {
      forceColor = false;
    } else if (hasFlag2("color") || hasFlag2("colors") || hasFlag2("color=true") || hasFlag2("color=always")) {
      forceColor = true;
    }
    if ("FORCE_COLOR" in env2) {
      forceColor = env2.FORCE_COLOR.length === 0 || parseInt(env2.FORCE_COLOR, 10) !== 0;
    }
    function translateLevel2(level) {
      if (level === 0) {
        return false;
      }
      return {
        level,
        hasBasic: true,
        has256: level >= 2,
        has16m: level >= 3
      };
    }
    function supportsColor2(stream) {
      if (forceColor === false) {
        return 0;
      }
      if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) {
        return 3;
      }
      if (hasFlag2("color=256")) {
        return 2;
      }
      if (stream && !stream.isTTY && forceColor !== true) {
        return 0;
      }
      var min2 = forceColor ? 1 : 0;
      if (process.platform === "win32") {
        var osRelease = os2.release().split(".");
        if (Number(process.versions.node.split(".")[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
          return Number(osRelease[2]) >= 14931 ? 3 : 2;
        }
        return 1;
      }
      if ("CI" in env2) {
        if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI"].some(function(sign) {
          return sign in env2;
        }) || env2.CI_NAME === "codeship") {
          return 1;
        }
        return min2;
      }
      if ("TEAMCITY_VERSION" in env2) {
        return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env2.TEAMCITY_VERSION) ? 1 : 0;
      }
      if ("TERM_PROGRAM" in env2) {
        var version2 = parseInt((env2.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
        switch (env2.TERM_PROGRAM) {
          case "iTerm.app":
            return version2 >= 3 ? 3 : 2;
          case "Hyper":
            return 3;
          case "Apple_Terminal":
            return 2;
        }
      }
      if (/-256(color)?$/i.test(env2.TERM)) {
        return 2;
      }
      if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env2.TERM)) {
        return 1;
      }
      if ("COLORTERM" in env2) {
        return 1;
      }
      if (env2.TERM === "dumb") {
        return min2;
      }
      return min2;
    }
    function getSupportLevel(stream) {
      var level = supportsColor2(stream);
      return translateLevel2(level);
    }
    module.exports = {
      supportsColor: getSupportLevel,
      stdout: getSupportLevel(process.stdout),
      stderr: getSupportLevel(process.stderr)
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/trap.js
var require_trap = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/trap.js"(exports, module) {
    "use strict";
    module["exports"] = function runTheTrap(text5, options) {
      var result = "";
      text5 = text5 || "Run the trap, drop the bass";
      text5 = text5.split("");
      var trap = {
        a: ["@", "\u0104", "\u023A", "\u0245", "\u0394", "\u039B", "\u0414"],
        b: ["\xDF", "\u0181", "\u0243", "\u026E", "\u03B2", "\u0E3F"],
        c: ["\xA9", "\u023B", "\u03FE"],
        d: ["\xD0", "\u018A", "\u0500", "\u0501", "\u0502", "\u0503"],
        e: [
          "\xCB",
          "\u0115",
          "\u018E",
          "\u0258",
          "\u03A3",
          "\u03BE",
          "\u04BC",
          "\u0A6C"
        ],
        f: ["\u04FA"],
        g: ["\u0262"],
        h: ["\u0126", "\u0195", "\u04A2", "\u04BA", "\u04C7", "\u050A"],
        i: ["\u0F0F"],
        j: ["\u0134"],
        k: ["\u0138", "\u04A0", "\u04C3", "\u051E"],
        l: ["\u0139"],
        m: ["\u028D", "\u04CD", "\u04CE", "\u0520", "\u0521", "\u0D69"],
        n: ["\xD1", "\u014B", "\u019D", "\u0376", "\u03A0", "\u048A"],
        o: [
          "\xD8",
          "\xF5",
          "\xF8",
          "\u01FE",
          "\u0298",
          "\u047A",
          "\u05DD",
          "\u06DD",
          "\u0E4F"
        ],
        p: ["\u01F7", "\u048E"],
        q: ["\u09CD"],
        r: ["\xAE", "\u01A6", "\u0210", "\u024C", "\u0280", "\u042F"],
        s: ["\xA7", "\u03DE", "\u03DF", "\u03E8"],
        t: ["\u0141", "\u0166", "\u0373"],
        u: ["\u01B1", "\u054D"],
        v: ["\u05D8"],
        w: ["\u0428", "\u0460", "\u047C", "\u0D70"],
        x: ["\u04B2", "\u04FE", "\u04FC", "\u04FD"],
        y: ["\xA5", "\u04B0", "\u04CB"],
        z: ["\u01B5", "\u0240"]
      };
      text5.forEach(function(c) {
        c = c.toLowerCase();
        var chars = trap[c] || [" "];
        var rand = Math.floor(Math.random() * chars.length);
        if (typeof trap[c] !== "undefined") {
          result += trap[c][rand];
        } else {
          result += c;
        }
      });
      return result;
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/zalgo.js
var require_zalgo = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/custom/zalgo.js"(exports, module) {
    "use strict";
    module["exports"] = function zalgo(text5, options) {
      text5 = text5 || "   he is here   ";
      var soul = {
        "up": [
          "\u030D",
          "\u030E",
          "\u0304",
          "\u0305",
          "\u033F",
          "\u0311",
          "\u0306",
          "\u0310",
          "\u0352",
          "\u0357",
          "\u0351",
          "\u0307",
          "\u0308",
          "\u030A",
          "\u0342",
          "\u0313",
          "\u0308",
          "\u034A",
          "\u034B",
          "\u034C",
          "\u0303",
          "\u0302",
          "\u030C",
          "\u0350",
          "\u0300",
          "\u0301",
          "\u030B",
          "\u030F",
          "\u0312",
          "\u0313",
          "\u0314",
          "\u033D",
          "\u0309",
          "\u0363",
          "\u0364",
          "\u0365",
          "\u0366",
          "\u0367",
          "\u0368",
          "\u0369",
          "\u036A",
          "\u036B",
          "\u036C",
          "\u036D",
          "\u036E",
          "\u036F",
          "\u033E",
          "\u035B",
          "\u0346",
          "\u031A"
        ],
        "down": [
          "\u0316",
          "\u0317",
          "\u0318",
          "\u0319",
          "\u031C",
          "\u031D",
          "\u031E",
          "\u031F",
          "\u0320",
          "\u0324",
          "\u0325",
          "\u0326",
          "\u0329",
          "\u032A",
          "\u032B",
          "\u032C",
          "\u032D",
          "\u032E",
          "\u032F",
          "\u0330",
          "\u0331",
          "\u0332",
          "\u0333",
          "\u0339",
          "\u033A",
          "\u033B",
          "\u033C",
          "\u0345",
          "\u0347",
          "\u0348",
          "\u0349",
          "\u034D",
          "\u034E",
          "\u0353",
          "\u0354",
          "\u0355",
          "\u0356",
          "\u0359",
          "\u035A",
          "\u0323"
        ],
        "mid": [
          "\u0315",
          "\u031B",
          "\u0300",
          "\u0301",
          "\u0358",
          "\u0321",
          "\u0322",
          "\u0327",
          "\u0328",
          "\u0334",
          "\u0335",
          "\u0336",
          "\u035C",
          "\u035D",
          "\u035E",
          "\u035F",
          "\u0360",
          "\u0362",
          "\u0338",
          "\u0337",
          "\u0361",
          " \u0489"
        ]
      };
      var all = [].concat(soul.up, soul.down, soul.mid);
      function randomNumber(range) {
        var r = Math.floor(Math.random() * range);
        return r;
      }
      function isChar(character) {
        var bool = false;
        all.filter(function(i) {
          bool = i === character;
        });
        return bool;
      }
      function heComes(text6, options2) {
        var result = "";
        var counts;
        var l;
        options2 = options2 || {};
        options2["up"] = typeof options2["up"] !== "undefined" ? options2["up"] : true;
        options2["mid"] = typeof options2["mid"] !== "undefined" ? options2["mid"] : true;
        options2["down"] = typeof options2["down"] !== "undefined" ? options2["down"] : true;
        options2["size"] = typeof options2["size"] !== "undefined" ? options2["size"] : "maxi";
        text6 = text6.split("");
        for (l in text6) {
          if (isChar(l)) {
            continue;
          }
          result = result + text6[l];
          counts = { "up": 0, "down": 0, "mid": 0 };
          switch (options2.size) {
            case "mini":
              counts.up = randomNumber(8);
              counts.mid = randomNumber(2);
              counts.down = randomNumber(8);
              break;
            case "maxi":
              counts.up = randomNumber(16) + 3;
              counts.mid = randomNumber(4) + 1;
              counts.down = randomNumber(64) + 3;
              break;
            default:
              counts.up = randomNumber(8) + 1;
              counts.mid = randomNumber(6) / 2;
              counts.down = randomNumber(8) + 1;
              break;
          }
          var arr = ["up", "mid", "down"];
          for (var d in arr) {
            var index6 = arr[d];
            for (var i = 0; i <= counts[index6]; i++) {
              if (options2[index6]) {
                result = result + soul[index6][randomNumber(soul[index6].length)];
              }
            }
          }
        }
        return result;
      }
      return heComes(text5, options);
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/america.js
var require_america = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/america.js"(exports, module) {
    "use strict";
    module["exports"] = function(colors) {
      return function(letter, i, exploded) {
        if (letter === " ") return letter;
        switch (i % 3) {
          case 0:
            return colors.red(letter);
          case 1:
            return colors.white(letter);
          case 2:
            return colors.blue(letter);
        }
      };
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/zebra.js
var require_zebra = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/zebra.js"(exports, module) {
    "use strict";
    module["exports"] = function(colors) {
      return function(letter, i, exploded) {
        return i % 2 === 0 ? letter : colors.inverse(letter);
      };
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/rainbow.js
var require_rainbow = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/rainbow.js"(exports, module) {
    "use strict";
    module["exports"] = function(colors) {
      var rainbowColors = ["red", "yellow", "green", "blue", "magenta"];
      return function(letter, i, exploded) {
        if (letter === " ") {
          return letter;
        } else {
          return colors[rainbowColors[i++ % rainbowColors.length]](letter);
        }
      };
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/random.js
var require_random = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/maps/random.js"(exports, module) {
    "use strict";
    module["exports"] = function(colors) {
      var available = [
        "underline",
        "inverse",
        "grey",
        "yellow",
        "red",
        "green",
        "blue",
        "white",
        "cyan",
        "magenta",
        "brightYellow",
        "brightRed",
        "brightGreen",
        "brightBlue",
        "brightWhite",
        "brightCyan",
        "brightMagenta"
      ];
      return function(letter, i, exploded) {
        return letter === " " ? letter : colors[available[Math.round(Math.random() * (available.length - 2))]](letter);
      };
    };
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/colors.js
var require_colors = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/lib/colors.js"(exports, module) {
    "use strict";
    var colors = {};
    module["exports"] = colors;
    colors.themes = {};
    var util2 = __require("util");
    var ansiStyles2 = colors.styles = require_styles();
    var defineProps = Object.defineProperties;
    var newLineRegex = new RegExp(/[\r\n]+/g);
    colors.supportsColor = require_supports_colors().supportsColor;
    if (typeof colors.enabled === "undefined") {
      colors.enabled = colors.supportsColor() !== false;
    }
    colors.enable = function() {
      colors.enabled = true;
    };
    colors.disable = function() {
      colors.enabled = false;
    };
    colors.stripColors = colors.strip = function(str) {
      return ("" + str).replace(/\x1B\[\d+m/g, "");
    };
    var stylize = colors.stylize = function stylize2(str, style) {
      if (!colors.enabled) {
        return str + "";
      }
      var styleMap = ansiStyles2[style];
      if (!styleMap && style in colors) {
        return colors[style](str);
      }
      return styleMap.open + str + styleMap.close;
    };
    var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
    var escapeStringRegexp = function(str) {
      if (typeof str !== "string") {
        throw new TypeError("Expected a string");
      }
      return str.replace(matchOperatorsRe, "\\$&");
    };
    function build(_styles) {
      var builder = function builder2() {
        return applyStyle2.apply(builder2, arguments);
      };
      builder._styles = _styles;
      builder.__proto__ = proto2;
      return builder;
    }
    var styles3 = function() {
      var ret = {};
      ansiStyles2.grey = ansiStyles2.gray;
      Object.keys(ansiStyles2).forEach(function(key) {
        ansiStyles2[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles2[key].close), "g");
        ret[key] = {
          get: function() {
            return build(this._styles.concat(key));
          }
        };
      });
      return ret;
    }();
    var proto2 = defineProps(function colors2() {
    }, styles3);
    function applyStyle2() {
      var args = Array.prototype.slice.call(arguments);
      var str = args.map(function(arg) {
        if (arg != null && arg.constructor === String) {
          return arg;
        } else {
          return util2.inspect(arg);
        }
      }).join(" ");
      if (!colors.enabled || !str) {
        return str;
      }
      var newLinesPresent = str.indexOf("\n") != -1;
      var nestedStyles = this._styles;
      var i = nestedStyles.length;
      while (i--) {
        var code = ansiStyles2[nestedStyles[i]];
        str = code.open + str.replace(code.closeRe, code.open) + code.close;
        if (newLinesPresent) {
          str = str.replace(newLineRegex, function(match2) {
            return code.close + match2 + code.open;
          });
        }
      }
      return str;
    }
    colors.setTheme = function(theme) {
      if (typeof theme === "string") {
        console.log("colors.setTheme now only accepts an object, not a string.  If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file.  The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));");
        return;
      }
      for (var style in theme) {
        (function(style2) {
          colors[style2] = function(str) {
            if (typeof theme[style2] === "object") {
              var out = str;
              for (var i in theme[style2]) {
                out = colors[theme[style2][i]](out);
              }
              return out;
            }
            return colors[theme[style2]](str);
          };
        })(style);
      }
    };
    function init() {
      var ret = {};
      Object.keys(styles3).forEach(function(name2) {
        ret[name2] = {
          get: function() {
            return build([name2]);
          }
        };
      });
      return ret;
    }
    var sequencer = function sequencer2(map2, str) {
      var exploded = str.split("");
      exploded = exploded.map(map2);
      return exploded.join("");
    };
    colors.trap = require_trap();
    colors.zalgo = require_zalgo();
    colors.maps = {};
    colors.maps.america = require_america()(colors);
    colors.maps.zebra = require_zebra()(colors);
    colors.maps.rainbow = require_rainbow()(colors);
    colors.maps.random = require_random()(colors);
    for (map in colors.maps) {
      (function(map2) {
        colors[map2] = function(str) {
          return sequencer(colors.maps[map2], str);
        };
      })(map);
    }
    var map;
    defineProps(colors, init());
  }
});

// ../node_modules/.pnpm/colors@1.4.0/node_modules/colors/safe.js
var require_safe = __commonJS({
  "../node_modules/.pnpm/colors@1.4.0/node_modules/colors/safe.js"(exports, module) {
    "use strict";
    var colors = require_colors();
    module["exports"] = colors;
  }
});

// ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/colorize.js
var require_colorize = __commonJS({
  "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/colorize.js"(exports, module) {
    "use strict";
    var color = require_safe();
    var { extendedTypeOf } = require_util();
    var Theme = {
      " "(s) {
        return s;
      },
      "+": color.green,
      "-": color.red
    };
    var subcolorizeToCallback = function(options, key, diff2, output, color2, indent) {
      let subvalue;
      const prefix2 = key ? `${key}: ` : "";
      const subindent = indent + "  ";
      const outputElisions = (n) => {
        const maxElisions = options.maxElisions === void 0 ? Infinity : options.maxElisions;
        if (n < maxElisions) {
          for (let i = 0; i < n; i++) {
            output(" ", subindent + "...");
          }
        } else {
          output(" ", subindent + `... (${n} entries)`);
        }
      };
      switch (extendedTypeOf(diff2)) {
        case "object":
          if ("__old" in diff2 && "__new" in diff2 && Object.keys(diff2).length === 2) {
            subcolorizeToCallback(options, key, diff2.__old, output, "-", indent);
            return subcolorizeToCallback(options, key, diff2.__new, output, "+", indent);
          } else {
            output(color2, `${indent}${prefix2}{`);
            for (const subkey of Object.keys(diff2)) {
              let m;
              subvalue = diff2[subkey];
              if (m = subkey.match(/^(.*)__deleted$/)) {
                subcolorizeToCallback(options, m[1], subvalue, output, "-", subindent);
              } else if (m = subkey.match(/^(.*)__added$/)) {
                subcolorizeToCallback(options, m[1], subvalue, output, "+", subindent);
              } else {
                subcolorizeToCallback(options, subkey, subvalue, output, color2, subindent);
              }
            }
            return output(color2, `${indent}}`);
          }
        case "array": {
          output(color2, `${indent}${prefix2}[`);
          let looksLikeDiff = true;
          for (const item of diff2) {
            if (extendedTypeOf(item) !== "array" || !(item.length === 2 || item.length === 1 && item[0] === " ") || !(typeof item[0] === "string") || item[0].length !== 1 || ![" ", "-", "+", "~"].includes(item[0])) {
              looksLikeDiff = false;
            }
          }
          if (looksLikeDiff) {
            let op;
            let elisionCount = 0;
            for ([op, subvalue] of diff2) {
              if (op === " " && subvalue == null) {
                elisionCount++;
              } else {
                if (elisionCount > 0) {
                  outputElisions(elisionCount);
                }
                elisionCount = 0;
                if (![" ", "~", "+", "-"].includes(op)) {
                  throw new Error(`Unexpected op '${op}' in ${JSON.stringify(diff2, null, 2)}`);
                }
                if (op === "~") {
                  op = " ";
                }
                subcolorizeToCallback(options, "", subvalue, output, op, subindent);
              }
            }
            if (elisionCount > 0) {
              outputElisions(elisionCount);
            }
          } else {
            for (subvalue of diff2) {
              subcolorizeToCallback(options, "", subvalue, output, color2, subindent);
            }
          }
          return output(color2, `${indent}]`);
        }
        default:
          if (diff2 === 0 || diff2 === null || diff2 === false || diff2 === "" || diff2) {
            return output(color2, indent + prefix2 + JSON.stringify(diff2));
          }
      }
    };
    var colorizeToCallback = (diff2, options, output) => subcolorizeToCallback(options, "", diff2, output, " ", "");
    var colorizeToArray = function(diff2, options = {}) {
      const output = [];
      colorizeToCallback(diff2, options, (color2, line2) => output.push(`${color2}${line2}`));
      return output;
    };
    var colorize = function(diff2, options = {}) {
      const output = [];
      colorizeToCallback(diff2, options, function(color2, line2) {
        if (options.color != null ? options.color : true) {
          return output.push(((options.theme != null ? options.theme[color2] : void 0) != null ? options.theme != null ? options.theme[color2] : void 0 : Theme[color2])(`${color2}${line2}`) + "\n");
        } else {
          return output.push(`${color2}${line2}
`);
        }
      });
      return output.join("");
    };
    module.exports = { colorize, colorizeToArray, colorizeToCallback };
  }
});

// ../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/index.js
var require_lib = __commonJS({
  "../node_modules/.pnpm/json-diff@1.0.6/node_modules/json-diff/lib/index.js"(exports, module) {
    "use strict";
    var { SequenceMatcher } = require_difflib2();
    var { extendedTypeOf, roundObj } = require_util();
    var { colorize, colorizeToCallback } = require_colorize();
    var JsonDiff = class {
      constructor(options) {
        options.outputKeys = options.outputKeys || [];
        options.excludeKeys = options.excludeKeys || [];
        this.options = options;
      }
      isScalar(obj) {
        return typeof obj !== "object" || obj === null;
      }
      objectDiff(obj1, obj2) {
        let result = {};
        let score = 0;
        let equal = true;
        for (const [key, value] of Object.entries(obj1)) {
          if (!this.options.outputNewOnly) {
            const postfix = "__deleted";
            if (!(key in obj2) && !this.options.excludeKeys.includes(key)) {
              result[`${key}${postfix}`] = value;
              score -= 30;
              equal = false;
            }
          }
        }
        for (const [key, value] of Object.entries(obj2)) {
          const postfix = !this.options.outputNewOnly ? "__added" : "";
          if (!(key in obj1) && !this.options.excludeKeys.includes(key)) {
            result[`${key}${postfix}`] = value;
            score -= 30;
            equal = false;
          }
        }
        for (const [key, value1] of Object.entries(obj1)) {
          if (key in obj2) {
            if (this.options.excludeKeys.includes(key)) {
              continue;
            }
            score += 20;
            const value2 = obj2[key];
            const change = this.diff(value1, value2);
            if (!change.equal) {
              result[key] = change.result;
              equal = false;
            } else if (this.options.full || this.options.outputKeys.includes(key)) {
              result[key] = value1;
            }
            score += Math.min(20, Math.max(-10, change.score / 5));
          }
        }
        if (equal) {
          score = 100 * Math.max(Object.keys(obj1).length, 0.5);
          if (!this.options.full) {
            result = void 0;
          }
        } else {
          score = Math.max(0, score);
        }
        return { score, result, equal };
      }
      findMatchingObject(item, index6, fuzzyOriginals) {
        let bestMatch = null;
        for (const [key, { item: candidate, index: matchIndex }] of Object.entries(fuzzyOriginals)) {
          if (key !== "__next") {
            const indexDistance = Math.abs(matchIndex - index6);
            if (extendedTypeOf(item) === extendedTypeOf(candidate)) {
              const { score } = this.diff(item, candidate);
              if (!bestMatch || score > bestMatch.score || score === bestMatch.score && indexDistance < bestMatch.indexDistance) {
                bestMatch = { score, key, indexDistance };
              }
            }
          }
        }
        return bestMatch;
      }
      scalarize(array2, originals, fuzzyOriginals) {
        const fuzzyMatches = [];
        if (fuzzyOriginals) {
          const keyScores = {};
          for (let index6 = 0; index6 < array2.length; index6++) {
            const item = array2[index6];
            if (this.isScalar(item)) {
              continue;
            }
            const bestMatch = this.findMatchingObject(item, index6, fuzzyOriginals);
            if (bestMatch && (!keyScores[bestMatch.key] || bestMatch.score > keyScores[bestMatch.key].score)) {
              keyScores[bestMatch.key] = { score: bestMatch.score, index: index6 };
            }
          }
          for (const [key, match2] of Object.entries(keyScores)) {
            fuzzyMatches[match2.index] = key;
          }
        }
        const result = [];
        for (let index6 = 0; index6 < array2.length; index6++) {
          const item = array2[index6];
          if (this.isScalar(item)) {
            result.push(item);
          } else {
            const key = fuzzyMatches[index6] || "__$!SCALAR" + originals.__next++;
            originals[key] = { item, index: index6 };
            result.push(key);
          }
        }
        return result;
      }
      isScalarized(item, originals) {
        return typeof item === "string" && item in originals;
      }
      descalarize(item, originals) {
        if (this.isScalarized(item, originals)) {
          return originals[item].item;
        } else {
          return item;
        }
      }
      arrayDiff(obj1, obj2) {
        const originals1 = { __next: 1 };
        const seq1 = this.scalarize(obj1, originals1);
        const originals2 = { __next: originals1.__next };
        const seq2 = this.scalarize(obj2, originals2, originals1);
        if (this.options.sort) {
          seq1.sort();
          seq2.sort();
        }
        const opcodes = new SequenceMatcher(null, seq1, seq2).getOpcodes();
        let result = [];
        let score = 0;
        let equal = true;
        for (const [op, i1, i2, j1, j2] of opcodes) {
          let i, j;
          let asc2, end;
          let asc1, end1;
          let asc22, end2;
          if (!(op === "equal" || this.options.keysOnly && op === "replace")) {
            equal = false;
          }
          switch (op) {
            case "equal":
              for (i = i1, end = i2, asc2 = i1 <= end; asc2 ? i < end : i > end; asc2 ? i++ : i--) {
                const item = seq1[i];
                if (this.isScalarized(item, originals1)) {
                  if (!this.isScalarized(item, originals2)) {
                    throw new Error(
                      `internal bug: isScalarized(item, originals1) != isScalarized(item, originals2) for item ${JSON.stringify(
                        item
                      )}`
                    );
                  }
                  const item1 = this.descalarize(item, originals1);
                  const item2 = this.descalarize(item, originals2);
                  const change = this.diff(item1, item2);
                  if (!change.equal) {
                    result.push(["~", change.result]);
                    equal = false;
                  } else {
                    if (this.options.full || this.options.keepUnchangedValues) {
                      result.push([" ", item1]);
                    } else {
                      result.push([" "]);
                    }
                  }
                } else {
                  if (this.options.full || this.options.keepUnchangedValues) {
                    result.push([" ", item]);
                  } else {
                    result.push([" "]);
                  }
                }
                score += 10;
              }
              break;
            case "delete":
              for (i = i1, end1 = i2, asc1 = i1 <= end1; asc1 ? i < end1 : i > end1; asc1 ? i++ : i--) {
                result.push(["-", this.descalarize(seq1[i], originals1)]);
                score -= 5;
              }
              break;
            case "insert":
              for (j = j1, end2 = j2, asc22 = j1 <= end2; asc22 ? j < end2 : j > end2; asc22 ? j++ : j--) {
                result.push(["+", this.descalarize(seq2[j], originals2)]);
                score -= 5;
              }
              break;
            case "replace":
              if (!this.options.keysOnly) {
                let asc3, end3;
                let asc4, end4;
                for (i = i1, end3 = i2, asc3 = i1 <= end3; asc3 ? i < end3 : i > end3; asc3 ? i++ : i--) {
                  result.push(["-", this.descalarize(seq1[i], originals1)]);
                  score -= 5;
                }
                for (j = j1, end4 = j2, asc4 = j1 <= end4; asc4 ? j < end4 : j > end4; asc4 ? j++ : j--) {
                  result.push(["+", this.descalarize(seq2[j], originals2)]);
                  score -= 5;
                }
              } else {
                let asc5, end5;
                for (i = i1, end5 = i2, asc5 = i1 <= end5; asc5 ? i < end5 : i > end5; asc5 ? i++ : i--) {
                  const change = this.diff(
                    this.descalarize(seq1[i], originals1),
                    this.descalarize(seq2[i - i1 + j1], originals2)
                  );
                  if (!change.equal) {
                    result.push(["~", change.result]);
                    equal = false;
                  } else {
                    result.push([" "]);
                  }
                }
              }
              break;
          }
        }
        if (equal || opcodes.length === 0) {
          if (!this.options.full) {
            result = void 0;
          } else {
            result = obj1;
          }
          score = 100;
        } else {
          score = Math.max(0, score);
        }
        return { score, result, equal };
      }
      diff(obj1, obj2) {
        const type1 = extendedTypeOf(obj1);
        const type2 = extendedTypeOf(obj2);
        if (type1 === type2) {
          switch (type1) {
            case "object":
              return this.objectDiff(obj1, obj2);
            case "array":
              return this.arrayDiff(obj1, obj2);
          }
        }
        let score = 100;
        let result = obj1;
        let equal;
        if (!this.options.keysOnly) {
          if (type1 === "date" && type2 === "date") {
            equal = obj1.getTime() === obj2.getTime();
          } else {
            equal = obj1 === obj2;
          }
          if (!equal) {
            score = 0;
            if (this.options.outputNewOnly) {
              result = obj2;
            } else {
              result = { __old: obj1, __new: obj2 };
            }
          } else if (!this.options.full) {
            result = void 0;
          }
        } else {
          equal = true;
          result = void 0;
        }
        return { score, result, equal };
      }
    };
    function diff2(obj1, obj2, options = {}) {
      if (options.precision !== void 0) {
        obj1 = roundObj(obj1, options.precision);
        obj2 = roundObj(obj2, options.precision);
      }
      return new JsonDiff(options).diff(obj1, obj2).result;
    }
    function diffString(obj1, obj2, options = {}) {
      return colorize(diff2(obj1, obj2, options), options);
    }
    module.exports = { diff: diff2, diffString, colorize, colorizeToCallback };
  }
});

// src/jsonDiffer.js
function diffSchemasOrTables(left, right) {
  left = JSON.parse(JSON.stringify(left));
  right = JSON.parse(JSON.stringify(right));
  const result = Object.entries((0, import_json_diff.diff)(left, right) ?? {});
  const added = result.filter((it) => it[0].endsWith("__added")).map((it) => it[1]);
  const deleted = result.filter((it) => it[0].endsWith("__deleted")).map((it) => it[1]);
  return { added, deleted };
}
function diffIndPolicies(left, right) {
  left = JSON.parse(JSON.stringify(left));
  right = JSON.parse(JSON.stringify(right));
  const result = Object.entries((0, import_json_diff.diff)(left, right) ?? {});
  const added = result.filter((it) => it[0].endsWith("__added")).map((it) => it[1]);
  const deleted = result.filter((it) => it[0].endsWith("__deleted")).map((it) => it[1]);
  return { added, deleted };
}
function diffColumns(left, right) {
  left = JSON.parse(JSON.stringify(left));
  right = JSON.parse(JSON.stringify(right));
  const result = (0, import_json_diff.diff)(left, right) ?? {};
  const alteredTables = Object.fromEntries(
    Object.entries(result).filter((it) => {
      return !(it[0].includes("__added") || it[0].includes("__deleted"));
    }).map((tableEntry) => {
      const deletedColumns = Object.entries(tableEntry[1].columns ?? {}).filter((it) => {
        return it[0].endsWith("__deleted");
      }).map((it) => {
        return it[1];
      });
      const addedColumns = Object.entries(tableEntry[1].columns ?? {}).filter((it) => {
        return it[0].endsWith("__added");
      }).map((it) => {
        return it[1];
      });
      tableEntry[1].columns = {
        added: addedColumns,
        deleted: deletedColumns
      };
      const table6 = left[tableEntry[0]];
      return [
        tableEntry[0],
        { name: table6.name, schema: table6.schema, ...tableEntry[1] }
      ];
    })
  );
  return alteredTables;
}
function diffPolicies(left, right) {
  left = JSON.parse(JSON.stringify(left));
  right = JSON.parse(JSON.stringify(right));
  const result = (0, import_json_diff.diff)(left, right) ?? {};
  const alteredTables = Object.fromEntries(
    Object.entries(result).filter((it) => {
      return !(it[0].includes("__added") || it[0].includes("__deleted"));
    }).map((tableEntry) => {
      const deletedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => {
        return it[0].endsWith("__deleted");
      }).map((it) => {
        return it[1];
      });
      const addedPolicies = Object.entries(tableEntry[1].policies ?? {}).filter((it) => {
        return it[0].endsWith("__added");
      }).map((it) => {
        return it[1];
      });
      tableEntry[1].policies = {
        added: addedPolicies,
        deleted: deletedPolicies
      };
      const table6 = left[tableEntry[0]];
      return [
        tableEntry[0],
        { name: table6.name, schema: table6.schema, ...tableEntry[1] }
      ];
    })
  );
  return alteredTables;
}
function applyJsonDiff(json1, json22) {
  json1 = JSON.parse(JSON.stringify(json1));
  json22 = JSON.parse(JSON.stringify(json22));
  const rawDiff = (0, import_json_diff.diff)(json1, json22);
  const difference = JSON.parse(JSON.stringify(rawDiff || {}));
  difference.schemas = difference.schemas || {};
  difference.tables = difference.tables || {};
  difference.enums = difference.enums || {};
  difference.sequences = difference.sequences || {};
  difference.roles = difference.roles || {};
  difference.policies = difference.policies || {};
  difference.views = difference.views || {};
  const schemaKeys = Object.keys(difference.schemas);
  for (let key of schemaKeys) {
    if (key.endsWith("__added") || key.endsWith("__deleted")) {
      delete difference.schemas[key];
      continue;
    }
  }
  const tableKeys = Object.keys(difference.tables);
  for (let key of tableKeys) {
    if (key.endsWith("__added") || key.endsWith("__deleted")) {
      delete difference.tables[key];
      continue;
    }
    const table6 = json1.tables[key];
    difference.tables[key] = {
      name: table6.name,
      schema: table6.schema,
      ...difference.tables[key]
    };
  }
  for (let [tableKey2, tableValue] of Object.entries(difference.tables)) {
    const table6 = difference.tables[tableKey2];
    const columns = tableValue.columns || {};
    const columnKeys = Object.keys(columns);
    for (let key of columnKeys) {
      if (key.endsWith("__added") || key.endsWith("__deleted")) {
        delete table6.columns[key];
        continue;
      }
    }
    if (Object.keys(columns).length === 0) {
      delete table6["columns"];
    }
    if ("name" in table6 && "schema" in table6 && Object.keys(table6).length === 2) {
      delete difference.tables[tableKey2];
    }
  }
  const enumsEntries = Object.entries(difference.enums);
  const alteredEnums = enumsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => {
    const enumEntry = json1.enums[it[0]];
    const { name: name2, schema: schema5, values } = enumEntry;
    const sequence = mapArraysDiff(values, it[1].values);
    const addedValues = sequence.filter((it2) => it2.type === "added").map((it2) => {
      return {
        before: it2.before,
        value: it2.value
      };
    });
    const deletedValues = sequence.filter((it2) => it2.type === "removed").map((it2) => it2.value);
    return { name: name2, schema: schema5, addedValues, deletedValues };
  });
  const sequencesEntries = Object.entries(difference.sequences);
  const alteredSequences = sequencesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted")) && "values" in it[1]).map((it) => {
    return json22.sequences[it[0]];
  });
  const rolesEntries = Object.entries(difference.roles);
  const alteredRoles = rolesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => {
    return json22.roles[it[0]];
  });
  const policiesEntries = Object.entries(difference.policies);
  const alteredPolicies = policiesEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map((it) => {
    return json22.policies[it[0]];
  });
  const viewsEntries = Object.entries(difference.views);
  const alteredViews = viewsEntries.filter((it) => !(it[0].includes("__added") || it[0].includes("__deleted"))).map(
    ([nameWithSchema, view5]) => {
      const deletedWithOption = view5.with__deleted;
      const addedWithOption = view5.with__added;
      const deletedWith = Object.fromEntries(
        Object.entries(view5.with || {}).filter((it) => it[0].endsWith("__deleted")).map(([key, value]) => {
          return [key.replace("__deleted", ""), value];
        })
      );
      const addedWith = Object.fromEntries(
        Object.entries(view5.with || {}).filter((it) => it[0].endsWith("__added")).map(([key, value]) => {
          return [key.replace("__added", ""), value];
        })
      );
      const alterWith = Object.fromEntries(
        Object.entries(view5.with || {}).filter(
          (it) => typeof it[1].__old !== "undefined" && typeof it[1].__new !== "undefined"
        ).map(
          (it) => {
            return [it[0], it[1].__new];
          }
        )
      );
      const alteredSchema = view5.schema;
      const alteredDefinition = view5.definition;
      const alteredExisting = view5.isExisting;
      const addedTablespace = view5.tablespace__added;
      const droppedTablespace = view5.tablespace__deleted;
      const alterTablespaceTo = view5.tablespace;
      let alteredTablespace;
      if (addedTablespace) alteredTablespace = { __new: addedTablespace, __old: "pg_default" };
      if (droppedTablespace) alteredTablespace = { __new: "pg_default", __old: droppedTablespace };
      if (alterTablespaceTo) alteredTablespace = alterTablespaceTo;
      const addedUsing = view5.using__added;
      const droppedUsing = view5.using__deleted;
      const alterUsingTo = view5.using;
      let alteredUsing;
      if (addedUsing) alteredUsing = { __new: addedUsing, __old: "heap" };
      if (droppedUsing) alteredUsing = { __new: "heap", __old: droppedUsing };
      if (alterUsingTo) alteredUsing = alterUsingTo;
      const alteredMeta = view5.meta;
      return Object.fromEntries(
        Object.entries({
          name: json22.views[nameWithSchema].name,
          schema: json22.views[nameWithSchema].schema,
          // pg
          deletedWithOption,
          addedWithOption,
          deletedWith: Object.keys(deletedWith).length ? deletedWith : void 0,
          addedWith: Object.keys(addedWith).length ? addedWith : void 0,
          alteredWith: Object.keys(alterWith).length ? alterWith : void 0,
          alteredSchema,
          alteredTablespace,
          alteredUsing,
          // mysql
          alteredMeta,
          // common
          alteredDefinition,
          alteredExisting
        }).filter(([_2, value]) => value !== void 0)
      );
    }
  );
  const alteredTablesWithColumns = Object.values(difference.tables).map(
    (table6) => {
      return findAlternationsInTable(table6);
    }
  );
  return {
    alteredTablesWithColumns,
    alteredEnums,
    alteredSequences,
    alteredRoles,
    alteredViews,
    alteredPolicies
  };
}
var import_json_diff, mapArraysDiff, findAlternationsInTable, alternationsInColumn;
var init_jsonDiffer = __esm({
  "src/jsonDiffer.js"() {
    "use strict";
    "use-strict";
    import_json_diff = __toESM(require_lib());
    mapArraysDiff = (source, diff2) => {
      const sequence = [];
      let sourceIndex = 0;
      for (let i = 0; i < diff2.length; i++) {
        const it = diff2[i];
        if (it.length === 1) {
          sequence.push({ type: "same", value: source[sourceIndex] });
          sourceIndex += 1;
        } else {
          if (it[0] === "-") {
            sequence.push({ type: "removed", value: it[1] });
          } else {
            sequence.push({ type: "added", value: it[1], before: "" });
          }
        }
      }
      const result = sequence.reverse().reduce(
        (acc, it) => {
          if (it.type === "same") {
            acc.prev = it.value;
          }
          if (it.type === "added" && acc.prev) {
            it.before = acc.prev;
          }
          acc.result.push(it);
          return acc;
        },
        { result: [] }
      );
      return result.result.reverse();
    };
    findAlternationsInTable = (table6) => {
      const columns = table6.columns ?? {};
      const altered = Object.keys(columns).filter((it) => !(it.includes("__deleted") || it.includes("__added"))).map((it) => {
        return { name: it, ...columns[it] };
      });
      const deletedIndexes = Object.fromEntries(
        Object.entries(table6.indexes__deleted || {}).concat(
          Object.entries(table6.indexes || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedIndexes = Object.fromEntries(
        Object.entries(table6.indexes__added || {}).concat(
          Object.entries(table6.indexes || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredIndexes = Object.fromEntries(
        Object.entries(table6.indexes || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const deletedPolicies = Object.fromEntries(
        Object.entries(table6.policies__deleted || {}).concat(
          Object.entries(table6.policies || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedPolicies = Object.fromEntries(
        Object.entries(table6.policies__added || {}).concat(
          Object.entries(table6.policies || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredPolicies = Object.fromEntries(
        Object.entries(table6.policies || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const deletedForeignKeys = Object.fromEntries(
        Object.entries(table6.foreignKeys__deleted || {}).concat(
          Object.entries(table6.foreignKeys || {}).filter((it) => it[0].includes("__deleted"))
        ).map((entry) => [entry[0].replace("__deleted", ""), entry[1]])
      );
      const addedForeignKeys = Object.fromEntries(
        Object.entries(table6.foreignKeys__added || {}).concat(
          Object.entries(table6.foreignKeys || {}).filter((it) => it[0].includes("__added"))
        ).map((entry) => [entry[0].replace("__added", ""), entry[1]])
      );
      const alteredForeignKeys = Object.fromEntries(
        Object.entries(table6.foreignKeys || {}).filter(
          (it) => !it[0].endsWith("__added") && !it[0].endsWith("__deleted")
        ).map((entry) => [entry[0], entry[1]])
      );
      const addedCompositePKs = Object.fromEntries(
        Object.entries(table6.compositePrimaryKeys || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedCompositePKs = Object.fromEntries(
        Object.entries(table6.compositePrimaryKeys || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredCompositePKs = Object.fromEntries(
        Object.entries(table6.compositePrimaryKeys || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const addedUniqueConstraints = Object.fromEntries(
        Object.entries(table6.uniqueConstraints || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedUniqueConstraints = Object.fromEntries(
        Object.entries(table6.uniqueConstraints || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredUniqueConstraints = Object.fromEntries(
        Object.entries(table6.uniqueConstraints || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const addedCheckConstraints = Object.fromEntries(
        Object.entries(table6.checkConstraints || {}).filter((it) => {
          return it[0].endsWith("__added");
        })
      );
      const deletedCheckConstraints = Object.fromEntries(
        Object.entries(table6.checkConstraints || {}).filter((it) => {
          return it[0].endsWith("__deleted");
        })
      );
      const alteredCheckConstraints = Object.fromEntries(
        Object.entries(table6.checkConstraints || {}).filter((it) => {
          return !it[0].endsWith("__deleted") && !it[0].endsWith("__added");
        })
      );
      const mappedAltered = altered.map((it) => alternationsInColumn(it)).filter(Boolean);
      return {
        name: table6.name,
        schema: table6.schema || "",
        altered: mappedAltered,
        addedIndexes,
        deletedIndexes,
        alteredIndexes,
        addedForeignKeys,
        deletedForeignKeys,
        alteredForeignKeys,
        addedCompositePKs,
        deletedCompositePKs,
        alteredCompositePKs,
        addedUniqueConstraints,
        deletedUniqueConstraints,
        alteredUniqueConstraints,
        deletedPolicies,
        addedPolicies,
        alteredPolicies,
        addedCheckConstraints,
        deletedCheckConstraints,
        alteredCheckConstraints
      };
    };
    alternationsInColumn = (column6) => {
      const altered = [column6];
      const result = altered.filter((it) => {
        if ("type" in it && it.type.__old.replace(" (", "(") === it.type.__new.replace(" (", "(")) {
          return false;
        }
        return true;
      }).map((it) => {
        if (typeof it.name !== "string" && "__old" in it.name) {
          return {
            ...it,
            name: { type: "changed", old: it.name.__old, new: it.name.__new }
          };
        }
        return it;
      }).map((it) => {
        if ("type" in it) {
          return {
            ...it,
            type: { type: "changed", old: it.type.__old, new: it.type.__new }
          };
        }
        return it;
      }).map((it) => {
        if ("default" in it) {
          return {
            ...it,
            default: {
              type: "changed",
              old: it.default.__old,
              new: it.default.__new
            }
          };
        }
        if ("default__added" in it) {
          const { default__added, ...others } = it;
          return {
            ...others,
            default: { type: "added", value: it.default__added }
          };
        }
        if ("default__deleted" in it) {
          const { default__deleted, ...others } = it;
          return {
            ...others,
            default: { type: "deleted", value: it.default__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("generated" in it) {
          if ("as" in it.generated && "type" in it.generated) {
            return {
              ...it,
              generated: {
                type: "changed",
                old: { as: it.generated.as.__old, type: it.generated.type.__old },
                new: { as: it.generated.as.__new, type: it.generated.type.__new }
              }
            };
          } else if ("as" in it.generated) {
            return {
              ...it,
              generated: {
                type: "changed",
                old: { as: it.generated.as.__old },
                new: { as: it.generated.as.__new }
              }
            };
          } else {
            return {
              ...it,
              generated: {
                type: "changed",
                old: { as: it.generated.type.__old },
                new: { as: it.generated.type.__new }
              }
            };
          }
        }
        if ("generated__added" in it) {
          const { generated__added, ...others } = it;
          return {
            ...others,
            generated: { type: "added", value: it.generated__added }
          };
        }
        if ("generated__deleted" in it) {
          const { generated__deleted, ...others } = it;
          return {
            ...others,
            generated: { type: "deleted", value: it.generated__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("identity" in it) {
          return {
            ...it,
            identity: {
              type: "changed",
              old: it.identity.__old,
              new: it.identity.__new
            }
          };
        }
        if ("identity__added" in it) {
          const { identity__added, ...others } = it;
          return {
            ...others,
            identity: { type: "added", value: it.identity__added }
          };
        }
        if ("identity__deleted" in it) {
          const { identity__deleted, ...others } = it;
          return {
            ...others,
            identity: { type: "deleted", value: it.identity__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("notNull" in it) {
          return {
            ...it,
            notNull: {
              type: "changed",
              old: it.notNull.__old,
              new: it.notNull.__new
            }
          };
        }
        if ("notNull__added" in it) {
          const { notNull__added, ...others } = it;
          return {
            ...others,
            notNull: { type: "added", value: it.notNull__added }
          };
        }
        if ("notNull__deleted" in it) {
          const { notNull__deleted, ...others } = it;
          return {
            ...others,
            notNull: { type: "deleted", value: it.notNull__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("primaryKey" in it) {
          return {
            ...it,
            primaryKey: {
              type: "changed",
              old: it.primaryKey.__old,
              new: it.primaryKey.__new
            }
          };
        }
        if ("primaryKey__added" in it) {
          const { notNull__added, ...others } = it;
          return {
            ...others,
            primaryKey: { type: "added", value: it.primaryKey__added }
          };
        }
        if ("primaryKey__deleted" in it) {
          const { notNull__deleted, ...others } = it;
          return {
            ...others,
            primaryKey: { type: "deleted", value: it.primaryKey__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("typeSchema" in it) {
          return {
            ...it,
            typeSchema: {
              type: "changed",
              old: it.typeSchema.__old,
              new: it.typeSchema.__new
            }
          };
        }
        if ("typeSchema__added" in it) {
          const { typeSchema__added, ...others } = it;
          return {
            ...others,
            typeSchema: { type: "added", value: it.typeSchema__added }
          };
        }
        if ("typeSchema__deleted" in it) {
          const { typeSchema__deleted, ...others } = it;
          return {
            ...others,
            typeSchema: { type: "deleted", value: it.typeSchema__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("onUpdate" in it) {
          return {
            ...it,
            onUpdate: {
              type: "changed",
              old: it.onUpdate.__old,
              new: it.onUpdate.__new
            }
          };
        }
        if ("onUpdate__added" in it) {
          const { onUpdate__added, ...others } = it;
          return {
            ...others,
            onUpdate: { type: "added", value: it.onUpdate__added }
          };
        }
        if ("onUpdate__deleted" in it) {
          const { onUpdate__deleted, ...others } = it;
          return {
            ...others,
            onUpdate: { type: "deleted", value: it.onUpdate__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("autoincrement" in it) {
          return {
            ...it,
            autoincrement: {
              type: "changed",
              old: it.autoincrement.__old,
              new: it.autoincrement.__new
            }
          };
        }
        if ("autoincrement__added" in it) {
          const { autoincrement__added, ...others } = it;
          return {
            ...others,
            autoincrement: { type: "added", value: it.autoincrement__added }
          };
        }
        if ("autoincrement__deleted" in it) {
          const { autoincrement__deleted, ...others } = it;
          return {
            ...others,
            autoincrement: { type: "deleted", value: it.autoincrement__deleted }
          };
        }
        return it;
      }).map((it) => {
        if ("" in it) {
          return {
            ...it,
            autoincrement: {
              type: "changed",
              old: it.autoincrement.__old,
              new: it.autoincrement.__new
            }
          };
        }
        if ("autoincrement__added" in it) {
          const { autoincrement__added, ...others } = it;
          return {
            ...others,
            autoincrement: { type: "added", value: it.autoincrement__added }
          };
        }
        if ("autoincrement__deleted" in it) {
          const { autoincrement__deleted, ...others } = it;
          return {
            ...others,
            autoincrement: { type: "deleted", value: it.autoincrement__deleted }
          };
        }
        return it;
      }).filter(Boolean);
      return result[0];
    };
  }
});

// src/sqlgenerator.ts
function fromJson(statements, dialect6, action, json22) {
  const result = statements.flatMap((statement) => {
    const filtered = convertors.filter((it) => {
      return it.can(statement, dialect6);
    });
    const convertor = filtered.length === 1 ? filtered[0] : void 0;
    if (!convertor) {
      return "";
    }
    return convertor.convert(statement, json22, action);
  }).filter((it) => it !== "");
  return result;
}
var parseType, Convertor, PgCreateRoleConvertor, PgDropRoleConvertor, PgRenameRoleConvertor, PgAlterRoleConvertor, PgCreatePolicyConvertor, PgDropPolicyConvertor, PgRenamePolicyConvertor, PgAlterPolicyConvertor, PgCreateIndPolicyConvertor, PgDropIndPolicyConvertor, PgRenameIndPolicyConvertor, PgAlterIndPolicyConvertor, PgEnableRlsConvertor, PgDisableRlsConvertor, PgCreateTableConvertor, MySqlCreateTableConvertor, SingleStoreCreateTableConvertor, SQLiteCreateTableConvertor, PgCreateViewConvertor, MySqlCreateViewConvertor, SqliteCreateViewConvertor, PgDropViewConvertor, MySqlDropViewConvertor, SqliteDropViewConvertor, MySqlAlterViewConvertor, PgRenameViewConvertor, MySqlRenameViewConvertor, PgAlterViewSchemaConvertor, PgAlterViewAddWithOptionConvertor, PgAlterViewDropWithOptionConvertor, PgAlterViewAlterTablespaceConvertor, PgAlterViewAlterUsingConvertor, PgAlterTableAlterColumnSetGenerated, PgAlterTableAlterColumnDropGenerated, PgAlterTableAlterColumnAlterGenerated, PgAlterTableAddUniqueConstraintConvertor, PgAlterTableDropUniqueConstraintConvertor, PgAlterTableAddCheckConstraintConvertor, PgAlterTableDeleteCheckConstraintConvertor, MySQLAlterTableAddUniqueConstraintConvertor, MySQLAlterTableDropUniqueConstraintConvertor, MySqlAlterTableAddCheckConstraintConvertor, SingleStoreAlterTableAddUniqueConstraintConvertor, SingleStoreAlterTableDropUniqueConstraintConvertor, MySqlAlterTableDeleteCheckConstraintConvertor, CreatePgSequenceConvertor, DropPgSequenceConvertor, RenamePgSequenceConvertor, MovePgSequenceConvertor, AlterPgSequenceConvertor, CreateTypeEnumConvertor, DropTypeEnumConvertor, AlterTypeAddValueConvertor, AlterTypeSetSchemaConvertor, AlterRenameTypeConvertor, AlterTypeDropValueConvertor, PgDropTableConvertor, MySQLDropTableConvertor, SingleStoreDropTableConvertor, SQLiteDropTableConvertor, PgRenameTableConvertor, SqliteRenameTableConvertor, MySqlRenameTableConvertor, SingleStoreRenameTableConvertor, PgAlterTableRenameColumnConvertor, MySqlAlterTableRenameColumnConvertor, SingleStoreAlterTableRenameColumnConvertor, SQLiteAlterTableRenameColumnConvertor, PgAlterTableDropColumnConvertor, MySqlAlterTableDropColumnConvertor, SingleStoreAlterTableDropColumnConvertor, SQLiteAlterTableDropColumnConvertor, PgAlterTableAddColumnConvertor, MySqlAlterTableAddColumnConvertor, SingleStoreAlterTableAddColumnConvertor, SQLiteAlterTableAddColumnConvertor, PgAlterTableAlterColumnSetTypeConvertor, PgAlterTableAlterColumnSetDefaultConvertor, PgAlterTableAlterColumnDropDefaultConvertor, PgAlterTableAlterColumnDropGeneratedConvertor, PgAlterTableAlterColumnSetExpressionConvertor, PgAlterTableAlterColumnAlterrGeneratedConvertor, SqliteAlterTableAlterColumnDropGeneratedConvertor, SqliteAlterTableAlterColumnSetExpressionConvertor, SqliteAlterTableAlterColumnAlterGeneratedConvertor, MySqlAlterTableAlterColumnAlterrGeneratedConvertor, MySqlAlterTableAddPk, MySqlAlterTableDropPk, LibSQLModifyColumn, MySqlModifyColumn, SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor, SingleStoreAlterTableAddPk, SingleStoreAlterTableDropPk, SingleStoreModifyColumn, PgAlterTableCreateCompositePrimaryKeyConvertor, PgAlterTableDeleteCompositePrimaryKeyConvertor, PgAlterTableAlterCompositePrimaryKeyConvertor, MySqlAlterTableCreateCompositePrimaryKeyConvertor, MySqlAlterTableDeleteCompositePrimaryKeyConvertor, MySqlAlterTableAlterCompositePrimaryKeyConvertor, PgAlterTableAlterColumnSetPrimaryKeyConvertor, PgAlterTableAlterColumnDropPrimaryKeyConvertor, PgAlterTableAlterColumnSetNotNullConvertor, PgAlterTableAlterColumnDropNotNullConvertor, PgCreateForeignKeyConvertor, LibSQLCreateForeignKeyConvertor, MySqlCreateForeignKeyConvertor, PgAlterForeignKeyConvertor, PgDeleteForeignKeyConvertor, MySqlDeleteForeignKeyConvertor, CreatePgIndexConvertor, CreateMySqlIndexConvertor, CreateSingleStoreIndexConvertor, CreateSqliteIndexConvertor, PgDropIndexConvertor, PgCreateSchemaConvertor, PgRenameSchemaConvertor, PgDropSchemaConvertor, PgAlterTableSetSchemaConvertor, PgAlterTableSetNewSchemaConvertor, PgAlterTableRemoveFromSchemaConvertor, SqliteDropIndexConvertor, MySqlDropIndexConvertor, SingleStoreDropIndexConvertor, SQLiteRecreateTableConvertor, LibSQLRecreateTableConvertor, SingleStoreRecreateTableConvertor, convertors;
var init_sqlgenerator = __esm({
  "src/sqlgenerator.ts"() {
    "use strict";
    init_migrate();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    init_utils();
    parseType = (schemaPrefix, type) => {
      const pgNativeTypes = [
        "uuid",
        "smallint",
        "integer",
        "bigint",
        "boolean",
        "text",
        "varchar",
        "serial",
        "bigserial",
        "decimal",
        "numeric",
        "real",
        "json",
        "jsonb",
        "time",
        "time with time zone",
        "time without time zone",
        "time",
        "timestamp",
        "timestamp with time zone",
        "timestamp without time zone",
        "date",
        "interval",
        "bigint",
        "bigserial",
        "double precision",
        "interval year",
        "interval month",
        "interval day",
        "interval hour",
        "interval minute",
        "interval second",
        "interval year to month",
        "interval day to hour",
        "interval day to minute",
        "interval day to second",
        "interval hour to minute",
        "interval hour to second",
        "interval minute to second",
        "char",
        "vector",
        "geometry",
        "halfvec",
        "sparsevec",
        "bit"
      ];
      const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g;
      const arrayDefinition = (type.match(arrayDefinitionRegex) ?? []).join("");
      const withoutArrayDefinition = type.replace(arrayDefinitionRegex, "");
      return pgNativeTypes.some((it) => type.startsWith(it)) ? `${withoutArrayDefinition}${arrayDefinition}` : `${schemaPrefix}"${withoutArrayDefinition}"${arrayDefinition}`;
    };
    Convertor = class {
    };
    PgCreateRoleConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_role" && dialect6 === "postgresql";
      }
      convert(statement) {
        return `CREATE ROLE "${statement.name}"${statement.values.createDb || statement.values.createRole || !statement.values.inherit ? ` WITH${statement.values.createDb ? " CREATEDB" : ""}${statement.values.createRole ? " CREATEROLE" : ""}${statement.values.inherit ? "" : " NOINHERIT"}` : ""};`;
      }
    };
    PgDropRoleConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_role" && dialect6 === "postgresql";
      }
      convert(statement) {
        return `DROP ROLE "${statement.name}";`;
      }
    };
    PgRenameRoleConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_role" && dialect6 === "postgresql";
      }
      convert(statement) {
        return `ALTER ROLE "${statement.nameFrom}" RENAME TO "${statement.nameTo}";`;
      }
    };
    PgAlterRoleConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_role" && dialect6 === "postgresql";
      }
      convert(statement) {
        return `ALTER ROLE "${statement.name}"${` WITH${statement.values.createDb ? " CREATEDB" : " NOCREATEDB"}${statement.values.createRole ? " CREATEROLE" : " NOCREATEROLE"}${statement.values.inherit ? " INHERIT" : " NOINHERIT"}`};`;
      }
    };
    PgCreatePolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const policy5 = statement.data;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        const usingPart = policy5.using ? ` USING (${policy5.using})` : "";
        const withCheckPart = policy5.withCheck ? ` WITH CHECK (${policy5.withCheck})` : "";
        const policyToPart = policy5.to?.map(
          (v) => ["current_user", "current_role", "session_user", "public"].includes(v) ? v : `"${v}"`
        ).join(", ");
        return `CREATE POLICY "${policy5.name}" ON ${tableNameWithSchema} AS ${policy5.as?.toUpperCase()} FOR ${policy5.for?.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`;
      }
    };
    PgDropPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const policy5 = statement.data;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `DROP POLICY "${policy5.name}" ON ${tableNameWithSchema} CASCADE;`;
      }
    };
    PgRenamePolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER POLICY "${statement.oldName}" ON ${tableNameWithSchema} RENAME TO "${statement.newName}";`;
      }
    };
    PgAlterPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_policy" && dialect6 === "postgresql";
      }
      convert(statement, _dialect, action) {
        const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(statement.newData) : PgSquasher.unsquashPolicy(statement.newData);
        const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(statement.oldData) : PgSquasher.unsquashPolicy(statement.oldData);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        const usingPart = newPolicy.using ? ` USING (${newPolicy.using})` : oldPolicy.using ? ` USING (${oldPolicy.using})` : "";
        const withCheckPart = newPolicy.withCheck ? ` WITH CHECK (${newPolicy.withCheck})` : oldPolicy.withCheck ? ` WITH CHECK  (${oldPolicy.withCheck})` : "";
        return `ALTER POLICY "${oldPolicy.name}" ON ${tableNameWithSchema} TO ${newPolicy.to}${usingPart}${withCheckPart};`;
      }
    };
    PgCreateIndPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_ind_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const policy5 = statement.data;
        const usingPart = policy5.using ? ` USING (${policy5.using})` : "";
        const withCheckPart = policy5.withCheck ? ` WITH CHECK (${policy5.withCheck})` : "";
        const policyToPart = policy5.to?.map(
          (v) => ["current_user", "current_role", "session_user", "public"].includes(v) ? v : `"${v}"`
        ).join(", ");
        return `CREATE POLICY "${policy5.name}" ON ${policy5.on} AS ${policy5.as?.toUpperCase()} FOR ${policy5.for?.toUpperCase()} TO ${policyToPart}${usingPart}${withCheckPart};`;
      }
    };
    PgDropIndPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_ind_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const policy5 = statement.data;
        return `DROP POLICY "${policy5.name}" ON ${policy5.on} CASCADE;`;
      }
    };
    PgRenameIndPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_ind_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        return `ALTER POLICY "${statement.oldName}" ON ${statement.tableKey} RENAME TO "${statement.newName}";`;
      }
    };
    PgAlterIndPolicyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_ind_policy" && dialect6 === "postgresql";
      }
      convert(statement) {
        const newPolicy = statement.newData;
        const oldPolicy = statement.oldData;
        const usingPart = newPolicy.using ? ` USING (${newPolicy.using})` : oldPolicy.using ? ` USING (${oldPolicy.using})` : "";
        const withCheckPart = newPolicy.withCheck ? ` WITH CHECK (${newPolicy.withCheck})` : oldPolicy.withCheck ? ` WITH CHECK  (${oldPolicy.withCheck})` : "";
        return `ALTER POLICY "${oldPolicy.name}" ON ${oldPolicy.on} TO ${newPolicy.to}${usingPart}${withCheckPart};`;
      }
    };
    PgEnableRlsConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "enable_rls" && dialect6 === "postgresql";
      }
      convert(statement) {
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ENABLE ROW LEVEL SECURITY;`;
      }
    };
    PgDisableRlsConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "disable_rls" && dialect6 === "postgresql";
      }
      convert(statement) {
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DISABLE ROW LEVEL SECURITY;`;
      }
    };
    PgCreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_table" && dialect6 === "postgresql";
      }
      convert(st) {
        const { tableName, schema: schema5, columns, compositePKs, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = st;
        let statement = "";
        const name2 = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        statement += `CREATE TABLE ${name2} (
`;
        for (let i = 0; i < columns.length; i++) {
          const column6 = columns[i];
          const primaryKeyStatement = column6.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column6.notNull && !column6.identity ? " NOT NULL" : "";
          const defaultStatement = column6.default !== void 0 ? ` DEFAULT ${column6.default}` : "";
          const uniqueConstraint6 = column6.isUnique ? ` CONSTRAINT "${column6.uniqueName}" UNIQUE${column6.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}` : "";
          const schemaPrefix = column6.typeSchema && column6.typeSchema !== "public" ? `"${column6.typeSchema}".` : "";
          const type = parseType(schemaPrefix, column6.type);
          const generated = column6.generated;
          const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated?.as}) STORED` : "";
          const unsquashedIdentity = column6.identity ? PgSquasher.unsquashIdentity(column6.identity) : void 0;
          const identityWithSchema = schema5 ? `"${schema5}"."${unsquashedIdentity?.name}"` : `"${unsquashedIdentity?.name}"`;
          const identity = unsquashedIdentity ? ` GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY (sequence name ${identityWithSchema}${unsquashedIdentity.increment ? ` INCREMENT BY ${unsquashedIdentity.increment}` : ""}${unsquashedIdentity.minValue ? ` MINVALUE ${unsquashedIdentity.minValue}` : ""}${unsquashedIdentity.maxValue ? ` MAXVALUE ${unsquashedIdentity.maxValue}` : ""}${unsquashedIdentity.startWith ? ` START WITH ${unsquashedIdentity.startWith}` : ""}${unsquashedIdentity.cache ? ` CACHE ${unsquashedIdentity.cache}` : ""}${unsquashedIdentity.cycle ? ` CYCLE` : ""})` : "";
          statement += `	"${column6.name}" ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${uniqueConstraint6}${identity}`;
          statement += i === columns.length - 1 ? "" : ",\n";
        }
        if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
          statement += ",\n";
          const compositePK6 = PgSquasher.unsquashPK(compositePKs[0]);
          statement += `	CONSTRAINT "${st.compositePkName}" PRIMARY KEY("${compositePK6.columns.join(`","`)}")`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint6 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = PgSquasher.unsquashUnique(uniqueConstraint6);
            statement += `	CONSTRAINT "${unsquashedUnique.name}" UNIQUE${unsquashedUnique.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}("${unsquashedUnique.columns.join(`","`)}")`;
          }
        }
        if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
          for (const checkConstraint5 of checkConstraints) {
            statement += ",\n";
            const unsquashedCheck = PgSquasher.unsquashCheck(checkConstraint5);
            statement += `	CONSTRAINT "${unsquashedCheck.name}" CHECK (${unsquashedCheck.value})`;
          }
        }
        statement += `
);`;
        statement += `
`;
        const enableRls = new PgEnableRlsConvertor().convert({
          type: "enable_rls",
          tableName,
          schema: schema5
        });
        return [statement, ...policies && policies.length > 0 || isRLSEnabled ? [enableRls] : []];
      }
    };
    MySqlCreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_table" && dialect6 === "mysql";
      }
      convert(st) {
        const {
          tableName,
          columns,
          schema: schema5,
          checkConstraints,
          compositePKs,
          uniqueConstraints,
          internals
        } = st;
        let statement = "";
        statement += `CREATE TABLE \`${tableName}\` (
`;
        for (let i = 0; i < columns.length; i++) {
          const column6 = columns[i];
          const primaryKeyStatement = column6.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column6.notNull ? " NOT NULL" : "";
          const defaultStatement = column6.default !== void 0 ? ` DEFAULT ${column6.default}` : "";
          const onUpdateStatement = column6.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          const autoincrementStatement = column6.autoincrement ? " AUTO_INCREMENT" : "";
          const generatedStatement = column6.generated ? ` GENERATED ALWAYS AS (${column6.generated?.as}) ${column6.generated?.type.toUpperCase()}` : "";
          statement += `	\`${column6.name}\` ${column6.type}${autoincrementStatement}${primaryKeyStatement}${generatedStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}`;
          statement += i === columns.length - 1 ? "" : ",\n";
        }
        if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
          statement += ",\n";
          const compositePK6 = MySqlSquasher.unsquashPK(compositePKs[0]);
          statement += `	CONSTRAINT \`${st.compositePkName}\` PRIMARY KEY(\`${compositePK6.columns.join(`\`,\``)}\`)`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint6 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = MySqlSquasher.unsquashUnique(uniqueConstraint6);
            const uniqueString = unsquashedUnique.columns.map((it) => {
              return internals?.indexes ? internals?.indexes[unsquashedUnique.name]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
            }).join(",");
            statement += `	CONSTRAINT \`${unsquashedUnique.name}\` UNIQUE(${uniqueString})`;
          }
        }
        if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
          for (const checkConstraint5 of checkConstraints) {
            statement += ",\n";
            const unsquashedCheck = MySqlSquasher.unsquashCheck(checkConstraint5);
            statement += `	CONSTRAINT \`${unsquashedCheck.name}\` CHECK(${unsquashedCheck.value})`;
          }
        }
        statement += `
);`;
        statement += `
`;
        return statement;
      }
    };
    SingleStoreCreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_table" && dialect6 === "singlestore";
      }
      convert(st) {
        const {
          tableName,
          columns,
          schema: schema5,
          compositePKs,
          uniqueConstraints,
          internals
        } = st;
        let statement = "";
        statement += `CREATE TABLE \`${tableName}\` (
`;
        for (let i = 0; i < columns.length; i++) {
          const column6 = columns[i];
          const primaryKeyStatement = column6.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column6.notNull ? " NOT NULL" : "";
          const defaultStatement = column6.default !== void 0 ? ` DEFAULT ${column6.default}` : "";
          const onUpdateStatement = column6.onUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          const autoincrementStatement = column6.autoincrement ? " AUTO_INCREMENT" : "";
          const generatedStatement = column6.generated ? ` GENERATED ALWAYS AS (${column6.generated?.as}) ${column6.generated?.type.toUpperCase()}` : "";
          statement += `	\`${column6.name}\` ${column6.type}${autoincrementStatement}${primaryKeyStatement}${notNullStatement}${defaultStatement}${onUpdateStatement}${generatedStatement}`;
          statement += i === columns.length - 1 ? "" : ",\n";
        }
        if (typeof compositePKs !== "undefined" && compositePKs.length > 0) {
          statement += ",\n";
          const compositePK6 = SingleStoreSquasher.unsquashPK(compositePKs[0]);
          statement += `	CONSTRAINT \`${compositePK6.name}\` PRIMARY KEY(\`${compositePK6.columns.join(`\`,\``)}\`)`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint6 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = SingleStoreSquasher.unsquashUnique(uniqueConstraint6);
            const uniqueString = unsquashedUnique.columns.map((it) => {
              return internals?.indexes ? internals?.indexes[unsquashedUnique.name]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
            }).join(",");
            statement += `	CONSTRAINT \`${unsquashedUnique.name}\` UNIQUE(${uniqueString})`;
          }
        }
        statement += `
);`;
        statement += `
`;
        return statement;
      }
    };
    SQLiteCreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "sqlite_create_table" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(st) {
        const {
          tableName,
          columns,
          referenceData,
          compositePKs,
          uniqueConstraints,
          checkConstraints
        } = st;
        let statement = "";
        statement += `CREATE TABLE \`${tableName}\` (
`;
        for (let i = 0; i < columns.length; i++) {
          const column6 = columns[i];
          const primaryKeyStatement = column6.primaryKey ? " PRIMARY KEY" : "";
          const notNullStatement = column6.notNull ? " NOT NULL" : "";
          const defaultStatement = column6.default !== void 0 ? ` DEFAULT ${column6.default}` : "";
          const autoincrementStatement = column6.autoincrement ? " AUTOINCREMENT" : "";
          const generatedStatement = column6.generated ? ` GENERATED ALWAYS AS ${column6.generated.as} ${column6.generated.type.toUpperCase()}` : "";
          statement += "	";
          statement += `\`${column6.name}\` ${column6.type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${generatedStatement}${notNullStatement}`;
          statement += i === columns.length - 1 ? "" : ",\n";
        }
        compositePKs.forEach((it) => {
          statement += ",\n	";
          statement += `PRIMARY KEY(${it.map((it2) => `\`${it2}\``).join(", ")})`;
        });
        for (let i = 0; i < referenceData.length; i++) {
          const {
            name: name2,
            tableFrom,
            tableTo,
            columnsFrom,
            columnsTo,
            onDelete,
            onUpdate
          } = referenceData[i];
          const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
          const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
          const fromColumnsString = columnsFrom.map((it) => `\`${it}\``).join(",");
          const toColumnsString = columnsTo.map((it) => `\`${it}\``).join(",");
          statement += ",";
          statement += "\n	";
          statement += `FOREIGN KEY (${fromColumnsString}) REFERENCES \`${tableTo}\`(${toColumnsString})${onUpdateStatement}${onDeleteStatement}`;
        }
        if (typeof uniqueConstraints !== "undefined" && uniqueConstraints.length > 0) {
          for (const uniqueConstraint6 of uniqueConstraints) {
            statement += ",\n";
            const unsquashedUnique = SQLiteSquasher.unsquashUnique(uniqueConstraint6);
            statement += `	CONSTRAINT ${unsquashedUnique.name} UNIQUE(\`${unsquashedUnique.columns.join(`\`,\``)}\`)`;
          }
        }
        if (typeof checkConstraints !== "undefined" && checkConstraints.length > 0) {
          for (const check of checkConstraints) {
            statement += ",\n";
            const { value, name: name2 } = SQLiteSquasher.unsquashCheck(check);
            statement += `	CONSTRAINT "${name2}" CHECK(${value})`;
          }
        }
        statement += `
`;
        statement += `);`;
        statement += `
`;
        return statement;
      }
    };
    PgCreateViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_view" && dialect6 === "postgresql";
      }
      convert(st) {
        const { definition, name: viewName, schema: schema5, with: withOption, materialized, withNoData, tablespace, using } = st;
        const name2 = schema5 ? `"${schema5}"."${viewName}"` : `"${viewName}"`;
        let statement = materialized ? `CREATE MATERIALIZED VIEW ${name2}` : `CREATE VIEW ${name2}`;
        if (using) statement += ` USING "${using}"`;
        const options = [];
        if (withOption) {
          statement += ` WITH (`;
          Object.entries(withOption).forEach(([key, value]) => {
            if (typeof value === "undefined") return;
            options.push(`${key.snake_case()} = ${value}`);
          });
          statement += options.join(", ");
          statement += `)`;
        }
        if (tablespace) statement += ` TABLESPACE ${tablespace}`;
        statement += ` AS (${definition})`;
        if (withNoData) statement += ` WITH NO DATA`;
        statement += `;`;
        return statement;
      }
    };
    MySqlCreateViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "mysql_create_view" && dialect6 === "mysql";
      }
      convert(st) {
        const { definition, name: name2, algorithm, sqlSecurity, withCheckOption, replace } = st;
        let statement = `CREATE `;
        statement += replace ? `OR REPLACE ` : "";
        statement += algorithm ? `ALGORITHM = ${algorithm}
` : "";
        statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
` : "";
        statement += `VIEW \`${name2}\` AS (${definition})`;
        statement += withCheckOption ? `
WITH ${withCheckOption} CHECK OPTION` : "";
        statement += ";";
        return statement;
      }
    };
    SqliteCreateViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "sqlite_create_view" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(st) {
        const { definition, name: name2 } = st;
        return `CREATE VIEW \`${name2}\` AS ${definition};`;
      }
    };
    PgDropViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_view" && dialect6 === "postgresql";
      }
      convert(st) {
        const { name: viewName, schema: schema5, materialized } = st;
        const name2 = schema5 ? `"${schema5}"."${viewName}"` : `"${viewName}"`;
        return `DROP${materialized ? " MATERIALIZED" : ""} VIEW ${name2};`;
      }
    };
    MySqlDropViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_view" && dialect6 === "mysql";
      }
      convert(st) {
        const { name: name2 } = st;
        return `DROP VIEW \`${name2}\`;`;
      }
    };
    SqliteDropViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_view" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(st) {
        const { name: name2 } = st;
        return `DROP VIEW \`${name2}\`;`;
      }
    };
    MySqlAlterViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_mysql_view" && dialect6 === "mysql";
      }
      convert(st) {
        const { name: name2, algorithm, definition, sqlSecurity, withCheckOption } = st;
        let statement = `ALTER `;
        statement += algorithm ? `ALGORITHM = ${algorithm}
` : "";
        statement += sqlSecurity ? `SQL SECURITY ${sqlSecurity}
` : "";
        statement += `VIEW \`${name2}\` AS ${definition}`;
        statement += withCheckOption ? `
WITH ${withCheckOption} CHECK OPTION` : "";
        statement += ";";
        return statement;
      }
    };
    PgRenameViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_view" && dialect6 === "postgresql";
      }
      convert(st) {
        const { nameFrom: from, nameTo: to, schema: schema5, materialized } = st;
        const nameFrom = `"${schema5}"."${from}"`;
        return `ALTER${materialized ? " MATERIALIZED" : ""} VIEW ${nameFrom} RENAME TO "${to}";`;
      }
    };
    MySqlRenameViewConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_view" && dialect6 === "mysql";
      }
      convert(st) {
        const { nameFrom: from, nameTo: to } = st;
        return `RENAME TABLE \`${from}\` TO \`${to}\`;`;
      }
    };
    PgAlterViewSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_view_alter_schema" && dialect6 === "postgresql";
      }
      convert(st) {
        const { fromSchema, toSchema, name: name2, materialized } = st;
        const statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${fromSchema}"."${name2}" SET SCHEMA "${toSchema}";`;
        return statement;
      }
    };
    PgAlterViewAddWithOptionConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_view_add_with_option" && dialect6 === "postgresql";
      }
      convert(st) {
        const { schema: schema5, with: withOption, name: name2, materialized } = st;
        let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema5}"."${name2}" SET (`;
        const options = [];
        Object.entries(withOption).forEach(([key, value]) => {
          options.push(`${key.snake_case()} = ${value}`);
        });
        statement += options.join(", ");
        statement += `);`;
        return statement;
      }
    };
    PgAlterViewDropWithOptionConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_view_drop_with_option" && dialect6 === "postgresql";
      }
      convert(st) {
        const { schema: schema5, name: name2, materialized, with: withOptions } = st;
        let statement = `ALTER${materialized ? " MATERIALIZED" : ""} VIEW "${schema5}"."${name2}" RESET (`;
        const options = [];
        Object.entries(withOptions).forEach(([key, value]) => {
          options.push(`${key.snake_case()}`);
        });
        statement += options.join(", ");
        statement += ");";
        return statement;
      }
    };
    PgAlterViewAlterTablespaceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_view_alter_tablespace" && dialect6 === "postgresql";
      }
      convert(st) {
        const { schema: schema5, name: name2, toTablespace } = st;
        const statement = `ALTER MATERIALIZED VIEW "${schema5}"."${name2}" SET TABLESPACE ${toTablespace};`;
        return statement;
      }
    };
    PgAlterViewAlterUsingConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_view_alter_using" && dialect6 === "postgresql";
      }
      convert(st) {
        const { schema: schema5, name: name2, toUsing } = st;
        const statement = `ALTER MATERIALIZED VIEW "${schema5}"."${name2}" SET ACCESS METHOD "${toUsing}";`;
        return statement;
      }
    };
    PgAlterTableAlterColumnSetGenerated = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_identity" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { identity, tableName, columnName, schema: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        const unsquashedIdentity = PgSquasher.unsquashIdentity(identity);
        const identityWithSchema = schema5 ? `"${schema5}"."${unsquashedIdentity?.name}"` : `"${unsquashedIdentity?.name}"`;
        const identityStatement = unsquashedIdentity ? ` GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY (sequence name ${identityWithSchema}${unsquashedIdentity.increment ? ` INCREMENT BY ${unsquashedIdentity.increment}` : ""}${unsquashedIdentity.minValue ? ` MINVALUE ${unsquashedIdentity.minValue}` : ""}${unsquashedIdentity.maxValue ? ` MAXVALUE ${unsquashedIdentity.maxValue}` : ""}${unsquashedIdentity.startWith ? ` START WITH ${unsquashedIdentity.startWith}` : ""}${unsquashedIdentity.cache ? ` CACHE ${unsquashedIdentity.cache}` : ""}${unsquashedIdentity.cycle ? ` CYCLE` : ""})` : "";
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" ADD${identityStatement};`;
      }
    };
    PgAlterTableAlterColumnDropGenerated = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_identity" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP IDENTITY;`;
      }
    };
    PgAlterTableAlterColumnAlterGenerated = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_change_identity" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { identity, oldIdentity, tableName, columnName, schema: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        const unsquashedIdentity = PgSquasher.unsquashIdentity(identity);
        const unsquashedOldIdentity = PgSquasher.unsquashIdentity(oldIdentity);
        const statementsToReturn = [];
        if (unsquashedOldIdentity.type !== unsquashedIdentity.type) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"};`
          );
        }
        if (unsquashedOldIdentity.minValue !== unsquashedIdentity.minValue) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET MINVALUE ${unsquashedIdentity.minValue};`
          );
        }
        if (unsquashedOldIdentity.maxValue !== unsquashedIdentity.maxValue) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET MAXVALUE ${unsquashedIdentity.maxValue};`
          );
        }
        if (unsquashedOldIdentity.increment !== unsquashedIdentity.increment) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET INCREMENT BY ${unsquashedIdentity.increment};`
          );
        }
        if (unsquashedOldIdentity.startWith !== unsquashedIdentity.startWith) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET START WITH ${unsquashedIdentity.startWith};`
          );
        }
        if (unsquashedOldIdentity.cache !== unsquashedIdentity.cache) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET CACHE ${unsquashedIdentity.cache};`
          );
        }
        if (unsquashedOldIdentity.cycle !== unsquashedIdentity.cycle) {
          statementsToReturn.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET ${unsquashedIdentity.cycle ? `CYCLE` : "NO CYCLE"};`
          );
        }
        return statementsToReturn;
      }
    };
    PgAlterTableAddUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_unique_constraint" && dialect6 === "postgresql";
      }
      convert(statement) {
        const unsquashed = PgSquasher.unsquashUnique(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${unsquashed.name}" UNIQUE${unsquashed.nullsNotDistinct ? " NULLS NOT DISTINCT" : ""}("${unsquashed.columns.join('","')}");`;
      }
    };
    PgAlterTableDropUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_unique_constraint" && dialect6 === "postgresql";
      }
      convert(statement) {
        const unsquashed = PgSquasher.unsquashUnique(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${unsquashed.name}";`;
      }
    };
    PgAlterTableAddCheckConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_check_constraint" && dialect6 === "postgresql";
      }
      convert(statement) {
        const unsquashed = PgSquasher.unsquashCheck(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${unsquashed.name}" CHECK (${unsquashed.value});`;
      }
    };
    PgAlterTableDeleteCheckConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_check_constraint" && dialect6 === "postgresql";
      }
      convert(statement) {
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.constraintName}";`;
      }
    };
    MySQLAlterTableAddUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_unique_constraint" && dialect6 === "mysql";
      }
      convert(statement) {
        const unsquashed = MySqlSquasher.unsquashUnique(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` UNIQUE(\`${unsquashed.columns.join("`,`")}\`);`;
      }
    };
    MySQLAlterTableDropUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_unique_constraint" && dialect6 === "mysql";
      }
      convert(statement) {
        const unsquashed = MySqlSquasher.unsquashUnique(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` DROP INDEX \`${unsquashed.name}\`;`;
      }
    };
    MySqlAlterTableAddCheckConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_check_constraint" && dialect6 === "mysql";
      }
      convert(statement) {
        const unsquashed = MySqlSquasher.unsquashCheck(statement.data);
        const { tableName } = statement;
        return `ALTER TABLE \`${tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` CHECK (${unsquashed.value});`;
      }
    };
    SingleStoreAlterTableAddUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_unique_constraint" && dialect6 === "singlestore";
      }
      convert(statement) {
        const unsquashed = SingleStoreSquasher.unsquashUnique(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` ADD CONSTRAINT \`${unsquashed.name}\` UNIQUE(\`${unsquashed.columns.join("`,`")}\`);`;
      }
    };
    SingleStoreAlterTableDropUniqueConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_unique_constraint" && dialect6 === "singlestore";
      }
      convert(statement) {
        const unsquashed = SingleStoreSquasher.unsquashUnique(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` DROP INDEX \`${unsquashed.name}\`;`;
      }
    };
    MySqlAlterTableDeleteCheckConstraintConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_check_constraint" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableName } = statement;
        return `ALTER TABLE \`${tableName}\` DROP CONSTRAINT \`${statement.constraintName}\`;`;
      }
    };
    CreatePgSequenceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_sequence" && dialect6 === "postgresql";
      }
      convert(st) {
        const { name: name2, values, schema: schema5 } = st;
        const sequenceWithSchema = schema5 ? `"${schema5}"."${name2}"` : `"${name2}"`;
        return `CREATE SEQUENCE ${sequenceWithSchema}${values.increment ? ` INCREMENT BY ${values.increment}` : ""}${values.minValue ? ` MINVALUE ${values.minValue}` : ""}${values.maxValue ? ` MAXVALUE ${values.maxValue}` : ""}${values.startWith ? ` START WITH ${values.startWith}` : ""}${values.cache ? ` CACHE ${values.cache}` : ""}${values.cycle ? ` CYCLE` : ""};`;
      }
    };
    DropPgSequenceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_sequence" && dialect6 === "postgresql";
      }
      convert(st) {
        const { name: name2, schema: schema5 } = st;
        const sequenceWithSchema = schema5 ? `"${schema5}"."${name2}"` : `"${name2}"`;
        return `DROP SEQUENCE ${sequenceWithSchema};`;
      }
    };
    RenamePgSequenceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_sequence" && dialect6 === "postgresql";
      }
      convert(st) {
        const { nameFrom, nameTo, schema: schema5 } = st;
        const sequenceWithSchemaFrom = schema5 ? `"${schema5}"."${nameFrom}"` : `"${nameFrom}"`;
        const sequenceWithSchemaTo = schema5 ? `"${schema5}"."${nameTo}"` : `"${nameTo}"`;
        return `ALTER SEQUENCE ${sequenceWithSchemaFrom} RENAME TO "${nameTo}";`;
      }
    };
    MovePgSequenceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "move_sequence" && dialect6 === "postgresql";
      }
      convert(st) {
        const { schemaFrom, schemaTo, name: name2 } = st;
        const sequenceWithSchema = schemaFrom ? `"${schemaFrom}"."${name2}"` : `"${name2}"`;
        const seqSchemaTo = schemaTo ? `"${schemaTo}"` : `public`;
        return `ALTER SEQUENCE ${sequenceWithSchema} SET SCHEMA ${seqSchemaTo};`;
      }
    };
    AlterPgSequenceConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_sequence" && dialect6 === "postgresql";
      }
      convert(st) {
        const { name: name2, schema: schema5, values } = st;
        const { increment, minValue, maxValue, startWith, cache, cycle } = values;
        const sequenceWithSchema = schema5 ? `"${schema5}"."${name2}"` : `"${name2}"`;
        return `ALTER SEQUENCE ${sequenceWithSchema}${increment ? ` INCREMENT BY ${increment}` : ""}${minValue ? ` MINVALUE ${minValue}` : ""}${maxValue ? ` MAXVALUE ${maxValue}` : ""}${startWith ? ` START WITH ${startWith}` : ""}${cache ? ` CACHE ${cache}` : ""}${cycle ? ` CYCLE` : ""};`;
      }
    };
    CreateTypeEnumConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "create_type_enum";
      }
      convert(st) {
        const { name: name2, values, schema: schema5 } = st;
        const enumNameWithSchema = schema5 ? `"${schema5}"."${name2}"` : `"${name2}"`;
        let valuesStatement = "(";
        valuesStatement += values.map((it) => `'${escapeSingleQuotes(it)}'`).join(", ");
        valuesStatement += ")";
        let statement = `CREATE TYPE ${enumNameWithSchema} AS ENUM${valuesStatement};`;
        return statement;
      }
    };
    DropTypeEnumConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "drop_type_enum";
      }
      convert(st) {
        const { name: name2, schema: schema5 } = st;
        const enumNameWithSchema = schema5 ? `"${schema5}"."${name2}"` : `"${name2}"`;
        let statement = `DROP TYPE ${enumNameWithSchema};`;
        return statement;
      }
    };
    AlterTypeAddValueConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "alter_type_add_value";
      }
      convert(st) {
        const { name: name2, schema: schema5, value, before } = st;
        const enumNameWithSchema = schema5 ? `"${schema5}"."${name2}"` : `"${name2}"`;
        return `ALTER TYPE ${enumNameWithSchema} ADD VALUE '${value}'${before.length ? ` BEFORE '${before}'` : ""};`;
      }
    };
    AlterTypeSetSchemaConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "move_type_enum";
      }
      convert(st) {
        const { name: name2, schemaFrom, schemaTo } = st;
        const enumNameWithSchema = schemaFrom ? `"${schemaFrom}"."${name2}"` : `"${name2}"`;
        return `ALTER TYPE ${enumNameWithSchema} SET SCHEMA "${schemaTo}";`;
      }
    };
    AlterRenameTypeConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "rename_type_enum";
      }
      convert(st) {
        const { nameTo, nameFrom, schema: schema5 } = st;
        const enumNameWithSchema = schema5 ? `"${schema5}"."${nameFrom}"` : `"${nameFrom}"`;
        return `ALTER TYPE ${enumNameWithSchema} RENAME TO "${nameTo}";`;
      }
    };
    AlterTypeDropValueConvertor = class extends Convertor {
      can(statement) {
        return statement.type === "alter_type_drop_value";
      }
      convert(st) {
        const { columnsWithEnum, name: name2, newValues, enumSchema: enumSchema4 } = st;
        const statements = [];
        for (const withEnum of columnsWithEnum) {
          const tableNameWithSchema = withEnum.tableSchema ? `"${withEnum.tableSchema}"."${withEnum.table}"` : `"${withEnum.table}"`;
          statements.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DATA TYPE text;`
          );
          if (withEnum.default) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DEFAULT ${withEnum.default}::text;`
            );
          }
        }
        statements.push(new DropTypeEnumConvertor().convert({ name: name2, schema: enumSchema4, type: "drop_type_enum" }));
        statements.push(new CreateTypeEnumConvertor().convert({
          name: name2,
          schema: enumSchema4,
          values: newValues,
          type: "create_type_enum"
        }));
        for (const withEnum of columnsWithEnum) {
          const tableNameWithSchema = withEnum.tableSchema ? `"${withEnum.tableSchema}"."${withEnum.table}"` : `"${withEnum.table}"`;
          const parsedType = parseType(`"${enumSchema4}".`, withEnum.columnType);
          if (withEnum.default) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DEFAULT ${withEnum.default}::${parsedType};`
            );
          }
          statements.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${withEnum.column}" SET DATA TYPE ${parsedType} USING "${withEnum.column}"::${parsedType};`
          );
        }
        return statements;
      }
    };
    PgDropTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_table" && dialect6 === "postgresql";
      }
      convert(statement, _d6, action) {
        const { tableName, schema: schema5, policies } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        const dropPolicyConvertor = new PgDropPolicyConvertor();
        const droppedPolicies = policies?.map((p) => {
          return dropPolicyConvertor.convert({
            type: "drop_policy",
            tableName,
            data: action === "push" ? PgSquasher.unsquashPolicyPush(p) : PgSquasher.unsquashPolicy(p),
            schema: schema5
          });
        }) ?? [];
        return [
          ...droppedPolicies,
          `DROP TABLE ${tableNameWithSchema} CASCADE;`
        ];
      }
    };
    MySQLDropTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_table" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableName } = statement;
        return `DROP TABLE \`${tableName}\`;`;
      }
    };
    SingleStoreDropTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_table" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableName } = statement;
        return `DROP TABLE \`${tableName}\`;`;
      }
    };
    SQLiteDropTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_table" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { tableName } = statement;
        return `DROP TABLE \`${tableName}\`;`;
      }
    };
    PgRenameTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_table" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableNameFrom, tableNameTo, toSchema, fromSchema } = statement;
        const from = fromSchema ? `"${fromSchema}"."${tableNameFrom}"` : `"${tableNameFrom}"`;
        const to = `"${tableNameTo}"`;
        return `ALTER TABLE ${from} RENAME TO ${to};`;
      }
    };
    SqliteRenameTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_table" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { tableNameFrom, tableNameTo } = statement;
        return `ALTER TABLE \`${tableNameFrom}\` RENAME TO \`${tableNameTo}\`;`;
      }
    };
    MySqlRenameTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_table" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableNameFrom, tableNameTo } = statement;
        return `RENAME TABLE \`${tableNameFrom}\` TO \`${tableNameTo}\`;`;
      }
    };
    SingleStoreRenameTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_table" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableNameFrom, tableNameTo } = statement;
        return `ALTER TABLE \`${tableNameFrom}\` RENAME TO \`${tableNameTo}\`;`;
      }
    };
    PgAlterTableRenameColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_rename_column" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, oldColumnName, newColumnName, schema: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} RENAME COLUMN "${oldColumnName}" TO "${newColumnName}";`;
      }
    };
    MySqlAlterTableRenameColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_rename_column" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableName, oldColumnName, newColumnName } = statement;
        return `ALTER TABLE \`${tableName}\` RENAME COLUMN \`${oldColumnName}\` TO \`${newColumnName}\`;`;
      }
    };
    SingleStoreAlterTableRenameColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_rename_column" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableName, oldColumnName, newColumnName } = statement;
        return `ALTER TABLE \`${tableName}\` CHANGE \`${oldColumnName}\` \`${newColumnName}\`;`;
      }
    };
    SQLiteAlterTableRenameColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_rename_column" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { tableName, oldColumnName, newColumnName } = statement;
        return `ALTER TABLE \`${tableName}\` RENAME COLUMN "${oldColumnName}" TO "${newColumnName}";`;
      }
    };
    PgAlterTableDropColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_drop_column" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP COLUMN "${columnName}";`;
      }
    };
    MySqlAlterTableDropColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_drop_column" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`;
      }
    };
    SingleStoreAlterTableDropColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_drop_column" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`;
      }
    };
    SQLiteAlterTableDropColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_drop_column" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        return `ALTER TABLE \`${tableName}\` DROP COLUMN \`${columnName}\`;`;
      }
    };
    PgAlterTableAddColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_add_column" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, column: column6, schema: schema5 } = statement;
        const { name: name2, type, notNull, generated, primaryKey, identity } = column6;
        const primaryKeyStatement = primaryKey ? " PRIMARY KEY" : "";
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        const defaultStatement = `${column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""}`;
        const schemaPrefix = column6.typeSchema && column6.typeSchema !== "public" ? `"${column6.typeSchema}".` : "";
        const fixedType = parseType(schemaPrefix, column6.type);
        const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
        const unsquashedIdentity = identity ? PgSquasher.unsquashIdentity(identity) : void 0;
        const identityWithSchema = schema5 ? `"${schema5}"."${unsquashedIdentity?.name}"` : `"${unsquashedIdentity?.name}"`;
        const identityStatement = unsquashedIdentity ? ` GENERATED ${unsquashedIdentity.type === "always" ? "ALWAYS" : "BY DEFAULT"} AS IDENTITY (sequence name ${identityWithSchema}${unsquashedIdentity.increment ? ` INCREMENT BY ${unsquashedIdentity.increment}` : ""}${unsquashedIdentity.minValue ? ` MINVALUE ${unsquashedIdentity.minValue}` : ""}${unsquashedIdentity.maxValue ? ` MAXVALUE ${unsquashedIdentity.maxValue}` : ""}${unsquashedIdentity.startWith ? ` START WITH ${unsquashedIdentity.startWith}` : ""}${unsquashedIdentity.cache ? ` CACHE ${unsquashedIdentity.cache}` : ""}${unsquashedIdentity.cycle ? ` CYCLE` : ""})` : "";
        const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated?.as}) STORED` : "";
        return `ALTER TABLE ${tableNameWithSchema} ADD COLUMN "${name2}" ${fixedType}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${identityStatement};`;
      }
    };
    MySqlAlterTableAddColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_add_column" && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableName, column: column6 } = statement;
        const {
          name: name2,
          type,
          notNull,
          primaryKey,
          autoincrement,
          onUpdate,
          generated
        } = column6;
        const defaultStatement = `${column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""}`;
        const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
        const primaryKeyStatement = `${primaryKey ? " PRIMARY KEY" : ""}`;
        const autoincrementStatement = `${autoincrement ? " AUTO_INCREMENT" : ""}`;
        const onUpdateStatement = `${onUpdate ? " ON UPDATE CURRENT_TIMESTAMP" : ""}`;
        const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated?.as}) ${generated?.type.toUpperCase()}` : "";
        return `ALTER TABLE \`${tableName}\` ADD \`${name2}\` ${type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${generatedStatement}${notNullStatement}${onUpdateStatement};`;
      }
    };
    SingleStoreAlterTableAddColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_add_column" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableName, column: column6 } = statement;
        const {
          name: name2,
          type,
          notNull,
          primaryKey,
          autoincrement,
          onUpdate,
          generated
        } = column6;
        const defaultStatement = `${column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""}`;
        const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
        const primaryKeyStatement = `${primaryKey ? " PRIMARY KEY" : ""}`;
        const autoincrementStatement = `${autoincrement ? " AUTO_INCREMENT" : ""}`;
        const onUpdateStatement = `${onUpdate ? " ON UPDATE CURRENT_TIMESTAMP" : ""}`;
        const generatedStatement = generated ? ` GENERATED ALWAYS AS (${generated?.as}) ${generated?.type.toUpperCase()}` : "";
        return `ALTER TABLE \`${tableName}\` ADD \`${name2}\` ${type}${primaryKeyStatement}${autoincrementStatement}${defaultStatement}${notNullStatement}${onUpdateStatement}${generatedStatement};`;
      }
    };
    SQLiteAlterTableAddColumnConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "sqlite_alter_table_add_column" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { tableName, column: column6, referenceData } = statement;
        const { name: name2, type, notNull, primaryKey, generated } = column6;
        const defaultStatement = `${column6.default !== void 0 ? ` DEFAULT ${column6.default}` : ""}`;
        const notNullStatement = `${notNull ? " NOT NULL" : ""}`;
        const primaryKeyStatement = `${primaryKey ? " PRIMARY KEY" : ""}`;
        const referenceAsObject = referenceData ? SQLiteSquasher.unsquashFK(referenceData) : void 0;
        const referenceStatement = `${referenceAsObject ? ` REFERENCES ${referenceAsObject.tableTo}(${referenceAsObject.columnsTo})` : ""}`;
        const generatedStatement = generated ? ` GENERATED ALWAYS AS ${generated.as} ${generated.type.toUpperCase()}` : "";
        return `ALTER TABLE \`${tableName}\` ADD \`${name2}\` ${type}${primaryKeyStatement}${defaultStatement}${generatedStatement}${notNullStatement}${referenceStatement};`;
      }
    };
    PgAlterTableAlterColumnSetTypeConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "pg_alter_table_alter_column_set_type" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, newDataType, schema: schema5, oldDataType, columnDefault, typeSchema } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        const statements = [];
        const type = parseType(`"${typeSchema}".`, newDataType.name);
        if (!oldDataType.isEnum && !newDataType.isEnum) {
          statements.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type};`
          );
          if (columnDefault) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};`
            );
          }
        }
        if (oldDataType.isEnum && !newDataType.isEnum) {
          statements.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type};`
          );
          if (columnDefault) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};`
            );
          }
        }
        if (!oldDataType.isEnum && newDataType.isEnum) {
          if (columnDefault) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault}::${type};`
            );
          }
          statements.push(
            `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type} USING "${columnName}"::${type};`
          );
        }
        if (oldDataType.isEnum && newDataType.isEnum) {
          const alterType = `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DATA TYPE ${type} USING "${columnName}"::text::${type};`;
          if (newDataType.name !== oldDataType.name && columnDefault) {
            statements.push(
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP DEFAULT;`,
              alterType,
              `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${columnDefault};`
            );
          } else {
            statements.push(alterType);
          }
        }
        return statements;
      }
    };
    PgAlterTableAlterColumnSetDefaultConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_default" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET DEFAULT ${statement.newDefaultValue};`;
      }
    };
    PgAlterTableAlterColumnDropDefaultConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_default" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP DEFAULT;`;
      }
    };
    PgAlterTableAlterColumnDropGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_generated" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP EXPRESSION;`;
      }
    };
    PgAlterTableAlterColumnSetExpressionConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_generated" && dialect6 === "postgresql";
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema5,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({
          schema: schema5,
          tableName,
          column: {
            name: columnName,
            type: statement.newDataType,
            notNull,
            default: columnDefault,
            onUpdate: columnOnUpdate,
            autoincrement: columnAutoIncrement,
            primaryKey: columnPk,
            generated: columnGenerated
          },
          type: "alter_table_add_column"
        });
        return [
          `ALTER TABLE ${tableNameWithSchema} drop column "${columnName}";`,
          addColumnStatement
        ];
      }
    };
    PgAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "postgresql";
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema5,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        const addColumnStatement = new PgAlterTableAddColumnConvertor().convert({
          schema: schema5,
          tableName,
          column: {
            name: columnName,
            type: statement.newDataType,
            notNull,
            default: columnDefault,
            onUpdate: columnOnUpdate,
            autoincrement: columnAutoIncrement,
            primaryKey: columnPk,
            generated: columnGenerated
          },
          type: "alter_table_add_column"
        });
        return [
          `ALTER TABLE ${tableNameWithSchema} drop column "${columnName}";`,
          addColumnStatement
        ];
      }
    };
    SqliteAlterTableAlterColumnDropGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_generated" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema5,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated,
          columnNotNull
        } = statement;
        const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert(
          {
            tableName,
            column: {
              name: columnName,
              type: statement.newDataType,
              notNull: columnNotNull,
              default: columnDefault,
              onUpdate: columnOnUpdate,
              autoincrement: columnAutoIncrement,
              primaryKey: columnPk,
              generated: columnGenerated
            },
            type: "sqlite_alter_table_add_column"
          }
        );
        const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({
          tableName,
          columnName,
          schema: schema5,
          type: "alter_table_drop_column"
        });
        return [dropColumnStatement, addColumnStatement];
      }
    };
    SqliteAlterTableAlterColumnSetExpressionConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_generated" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema5,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert(
          {
            tableName,
            column: {
              name: columnName,
              type: statement.newDataType,
              notNull,
              default: columnDefault,
              onUpdate: columnOnUpdate,
              autoincrement: columnAutoIncrement,
              primaryKey: columnPk,
              generated: columnGenerated
            },
            type: "sqlite_alter_table_add_column"
          }
        );
        const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({
          tableName,
          columnName,
          schema: schema5,
          type: "alter_table_drop_column"
        });
        return [dropColumnStatement, addColumnStatement];
      }
    };
    SqliteAlterTableAlterColumnAlterGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_alter_generated" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema5,
          columnNotNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const addColumnStatement = new SQLiteAlterTableAddColumnConvertor().convert(
          {
            tableName,
            column: {
              name: columnName,
              type: statement.newDataType,
              notNull: columnNotNull,
              default: columnDefault,
              onUpdate: columnOnUpdate,
              autoincrement: columnAutoIncrement,
              primaryKey: columnPk,
              generated: columnGenerated
            },
            type: "sqlite_alter_table_add_column"
          }
        );
        const dropColumnStatement = new SQLiteAlterTableDropColumnConvertor().convert({
          tableName,
          columnName,
          schema: schema5,
          type: "alter_table_drop_column"
        });
        return [dropColumnStatement, addColumnStatement];
      }
    };
    MySqlAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "mysql";
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema5,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema5 ? `\`${schema5}\`.\`${tableName}\`` : `\`${tableName}\``;
        const addColumnStatement = new MySqlAlterTableAddColumnConvertor().convert({
          schema: schema5,
          tableName,
          column: {
            name: columnName,
            type: statement.newDataType,
            notNull,
            default: columnDefault,
            onUpdate: columnOnUpdate,
            autoincrement: columnAutoIncrement,
            primaryKey: columnPk,
            generated: columnGenerated
          },
          type: "alter_table_add_column"
        });
        return [
          `ALTER TABLE ${tableNameWithSchema} drop column \`${columnName}\`;`,
          addColumnStatement
        ];
      }
    };
    MySqlAlterTableAddPk = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "mysql";
      }
      convert(statement) {
        return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY (\`${statement.columnName}\`);`;
      }
    };
    MySqlAlterTableDropPk = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "mysql";
      }
      convert(statement) {
        return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY`;
      }
    };
    LibSQLModifyColumn = class extends Convertor {
      can(statement, dialect6) {
        return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") && dialect6 === "turso";
      }
      convert(statement, json22) {
        const { tableName, columnName } = statement;
        let columnType = ``;
        let columnDefault = "";
        let columnNotNull = "";
        const sqlStatements = [];
        const indexes = [];
        for (const table6 of Object.values(json22.tables)) {
          for (const index6 of Object.values(table6.indexes)) {
            const unsquashed = SQLiteSquasher.unsquashIdx(index6);
            sqlStatements.push(`DROP INDEX "${unsquashed.name}";`);
            indexes.push({ ...unsquashed, tableName: table6.name });
          }
        }
        switch (statement.type) {
          case "alter_table_alter_column_set_type":
            columnType = ` ${statement.newDataType}`;
            columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
            columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
            break;
          case "alter_table_alter_column_drop_notnull":
            columnType = ` ${statement.newDataType}`;
            columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
            columnNotNull = "";
            break;
          case "alter_table_alter_column_set_notnull":
            columnType = ` ${statement.newDataType}`;
            columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
            columnNotNull = ` NOT NULL`;
            break;
          case "alter_table_alter_column_set_default":
            columnType = ` ${statement.newDataType}`;
            columnDefault = ` DEFAULT ${statement.newDefaultValue}`;
            columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
            break;
          case "alter_table_alter_column_drop_default":
            columnType = ` ${statement.newDataType}`;
            columnDefault = "";
            columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
            break;
        }
        columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault;
        sqlStatements.push(
          `ALTER TABLE \`${tableName}\` ALTER COLUMN "${columnName}" TO "${columnName}"${columnType}${columnNotNull}${columnDefault};`
        );
        for (const index6 of indexes) {
          const indexPart = index6.isUnique ? "UNIQUE INDEX" : "INDEX";
          const whereStatement = index6.where ? ` WHERE ${index6.where}` : "";
          const uniqueString = index6.columns.map((it) => `\`${it}\``).join(",");
          const tableName2 = index6.tableName;
          sqlStatements.push(
            `CREATE ${indexPart} \`${index6.name}\` ON \`${tableName2}\` (${uniqueString})${whereStatement};`
          );
        }
        return sqlStatements;
      }
    };
    MySqlModifyColumn = class extends Convertor {
      can(statement, dialect6) {
        return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_on_update" || statement.type === "alter_table_alter_column_set_on_update" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_generated" || statement.type === "alter_table_alter_column_drop_generated") && dialect6 === "mysql";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        let columnType = ``;
        let columnDefault = "";
        let columnNotNull = "";
        let columnOnUpdate = "";
        let columnAutoincrement = "";
        let primaryKey = statement.columnPk ? " PRIMARY KEY" : "";
        let columnGenerated = "";
        if (statement.type === "alter_table_alter_column_drop_notnull") {
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_notnull") {
          columnNotNull = ` NOT NULL`;
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_drop_on_update") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnOnUpdate = "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_on_update") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = ` ON UPDATE CURRENT_TIMESTAMP`;
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_autoincrement") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = " AUTO_INCREMENT";
        } else if (statement.type === "alter_table_alter_column_drop_autoincrement") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = "";
        } else if (statement.type === "alter_table_alter_column_set_default") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = ` DEFAULT ${statement.newDefaultValue}`;
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_drop_default") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_generated") {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          if (statement.columnGenerated?.type === "virtual") {
            return [
              new MySqlAlterTableDropColumnConvertor().convert({
                type: "alter_table_drop_column",
                tableName: statement.tableName,
                columnName: statement.columnName,
                schema: statement.schema
              }),
              new MySqlAlterTableAddColumnConvertor().convert({
                tableName,
                column: {
                  name: columnName,
                  type: statement.newDataType,
                  notNull: statement.columnNotNull,
                  default: statement.columnDefault,
                  onUpdate: statement.columnOnUpdate,
                  autoincrement: statement.columnAutoIncrement,
                  primaryKey: statement.columnPk,
                  generated: statement.columnGenerated
                },
                schema: statement.schema,
                type: "alter_table_add_column"
              })
            ];
          } else {
            columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${statement.columnGenerated?.as}) ${statement.columnGenerated?.type.toUpperCase()}` : "";
          }
        } else if (statement.type === "alter_table_alter_column_drop_generated") {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          if (statement.oldColumn?.generated?.type === "virtual") {
            return [
              new MySqlAlterTableDropColumnConvertor().convert({
                type: "alter_table_drop_column",
                tableName: statement.tableName,
                columnName: statement.columnName,
                schema: statement.schema
              }),
              new MySqlAlterTableAddColumnConvertor().convert({
                tableName,
                column: {
                  name: columnName,
                  type: statement.newDataType,
                  notNull: statement.columnNotNull,
                  default: statement.columnDefault,
                  onUpdate: statement.columnOnUpdate,
                  autoincrement: statement.columnAutoIncrement,
                  primaryKey: statement.columnPk,
                  generated: statement.columnGenerated
                },
                schema: statement.schema,
                type: "alter_table_add_column"
              })
            ];
          }
        } else {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${statement.columnGenerated?.as}) ${statement.columnGenerated?.type.toUpperCase()}` : "";
        }
        columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault;
        return `ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${columnName}\`${columnType}${columnAutoincrement}${columnGenerated}${columnNotNull}${columnDefault}${columnOnUpdate};`;
      }
    };
    SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_alter_generated" && dialect6 === "singlestore";
      }
      convert(statement) {
        const {
          tableName,
          columnName,
          schema: schema5,
          columnNotNull: notNull,
          columnDefault,
          columnOnUpdate,
          columnAutoIncrement,
          columnPk,
          columnGenerated
        } = statement;
        const tableNameWithSchema = schema5 ? `\`${schema5}\`.\`${tableName}\`` : `\`${tableName}\``;
        const addColumnStatement = new SingleStoreAlterTableAddColumnConvertor().convert({
          schema: schema5,
          tableName,
          column: {
            name: columnName,
            type: statement.newDataType,
            notNull,
            default: columnDefault,
            onUpdate: columnOnUpdate,
            autoincrement: columnAutoIncrement,
            primaryKey: columnPk,
            generated: columnGenerated
          },
          type: "alter_table_add_column"
        });
        return [
          `ALTER TABLE ${tableNameWithSchema} drop column \`${columnName}\`;`,
          addColumnStatement
        ];
      }
    };
    SingleStoreAlterTableAddPk = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "singlestore";
      }
      convert(statement) {
        return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY (\`${statement.columnName}\`);`;
      }
    };
    SingleStoreAlterTableDropPk = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "singlestore";
      }
      convert(statement) {
        return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY`;
      }
    };
    SingleStoreModifyColumn = class extends Convertor {
      can(statement, dialect6) {
        return (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_on_update" || statement.type === "alter_table_alter_column_set_on_update" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_generated" || statement.type === "alter_table_alter_column_drop_generated") && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        let columnType = ``;
        let columnDefault = "";
        let columnNotNull = "";
        let columnOnUpdate = "";
        let columnAutoincrement = "";
        let primaryKey = statement.columnPk ? " PRIMARY KEY" : "";
        let columnGenerated = "";
        if (statement.type === "alter_table_alter_column_drop_notnull") {
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_notnull") {
          columnNotNull = ` NOT NULL`;
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_drop_on_update") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnOnUpdate = "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_on_update") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = ` ON UPDATE CURRENT_TIMESTAMP`;
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_autoincrement") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = " AUTO_INCREMENT";
        } else if (statement.type === "alter_table_alter_column_drop_autoincrement") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = "";
        } else if (statement.type === "alter_table_alter_column_set_default") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = ` DEFAULT ${statement.newDefaultValue}`;
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_drop_default") {
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnType = ` ${statement.newDataType}`;
          columnDefault = "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
        } else if (statement.type === "alter_table_alter_column_set_generated") {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          if (statement.columnGenerated?.type === "virtual") {
            return [
              new SingleStoreAlterTableDropColumnConvertor().convert({
                type: "alter_table_drop_column",
                tableName: statement.tableName,
                columnName: statement.columnName,
                schema: statement.schema
              }),
              new SingleStoreAlterTableAddColumnConvertor().convert({
                tableName,
                column: {
                  name: columnName,
                  type: statement.newDataType,
                  notNull: statement.columnNotNull,
                  default: statement.columnDefault,
                  onUpdate: statement.columnOnUpdate,
                  autoincrement: statement.columnAutoIncrement,
                  primaryKey: statement.columnPk,
                  generated: statement.columnGenerated
                },
                schema: statement.schema,
                type: "alter_table_add_column"
              })
            ];
          } else {
            columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${statement.columnGenerated?.as}) ${statement.columnGenerated?.type.toUpperCase()}` : "";
          }
        } else if (statement.type === "alter_table_alter_column_drop_generated") {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          if (statement.oldColumn?.generated?.type === "virtual") {
            return [
              new SingleStoreAlterTableDropColumnConvertor().convert({
                type: "alter_table_drop_column",
                tableName: statement.tableName,
                columnName: statement.columnName,
                schema: statement.schema
              }),
              new SingleStoreAlterTableAddColumnConvertor().convert({
                tableName,
                column: {
                  name: columnName,
                  type: statement.newDataType,
                  notNull: statement.columnNotNull,
                  default: statement.columnDefault,
                  onUpdate: statement.columnOnUpdate,
                  autoincrement: statement.columnAutoIncrement,
                  primaryKey: statement.columnPk,
                  generated: statement.columnGenerated
                },
                schema: statement.schema,
                type: "alter_table_add_column"
              })
            ];
          }
        } else {
          columnType = ` ${statement.newDataType}`;
          columnNotNull = statement.columnNotNull ? ` NOT NULL` : "";
          columnOnUpdate = columnOnUpdate = statement.columnOnUpdate ? ` ON UPDATE CURRENT_TIMESTAMP` : "";
          columnDefault = statement.columnDefault ? ` DEFAULT ${statement.columnDefault}` : "";
          columnAutoincrement = statement.columnAutoIncrement ? " AUTO_INCREMENT" : "";
          columnGenerated = statement.columnGenerated ? ` GENERATED ALWAYS AS (${statement.columnGenerated?.as}) ${statement.columnGenerated?.type.toUpperCase()}` : "";
        }
        columnDefault = columnDefault instanceof Date ? columnDefault.toISOString() : columnDefault;
        return `ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${columnName}\`${columnType}${columnAutoincrement}${columnNotNull}${columnDefault}${columnOnUpdate}${columnGenerated};`;
      }
    };
    PgAlterTableCreateCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_composite_pk" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { name: name2, columns } = PgSquasher.unsquashPK(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${statement.constraintName}" PRIMARY KEY("${columns.join('","')}");`;
      }
    };
    PgAlterTableDeleteCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_composite_pk" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { name: name2, columns } = PgSquasher.unsquashPK(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.constraintName}";`;
      }
    };
    PgAlterTableAlterCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_composite_pk" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { name: name2, columns } = PgSquasher.unsquashPK(statement.old);
        const { name: newName, columns: newColumns } = PgSquasher.unsquashPK(
          statement.new
        );
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${statement.oldConstraintName}";
${BREAKPOINT}ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${statement.newConstraintName}" PRIMARY KEY("${newColumns.join('","')}");`;
      }
    };
    MySqlAlterTableCreateCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_composite_pk" && dialect6 === "mysql";
      }
      convert(statement) {
        const { name: name2, columns } = MySqlSquasher.unsquashPK(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` ADD PRIMARY KEY(\`${columns.join("`,`")}\`);`;
      }
    };
    MySqlAlterTableDeleteCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_composite_pk" && dialect6 === "mysql";
      }
      convert(statement) {
        const { name: name2, columns } = MySqlSquasher.unsquashPK(statement.data);
        return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY;`;
      }
    };
    MySqlAlterTableAlterCompositePrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_composite_pk" && dialect6 === "mysql";
      }
      convert(statement) {
        const { name: name2, columns } = MySqlSquasher.unsquashPK(statement.old);
        const { name: newName, columns: newColumns } = MySqlSquasher.unsquashPK(
          statement.new
        );
        return `ALTER TABLE \`${statement.tableName}\` DROP PRIMARY KEY, ADD PRIMARY KEY(\`${newColumns.join("`,`")}\`);`;
      }
    };
    PgAlterTableAlterColumnSetPrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_pk" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ADD PRIMARY KEY ("${columnName}");`;
      }
    };
    PgAlterTableAlterColumnDropPrimaryKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_pk" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName, schema: schema5 } = statement;
        return `/* 
    Unfortunately in current drizzle-kit version we can't automatically get name for primary key.
    We are working on making it available!

    Meanwhile you can:
        1. Check pk name in your database, by running
            SELECT constraint_name FROM information_schema.table_constraints
            WHERE table_schema = '${typeof schema5 === "undefined" || schema5 === "" ? "public" : schema5}'
                AND table_name = '${tableName}'
                AND constraint_type = 'PRIMARY KEY';
        2. Uncomment code below and paste pk name manually
        
    Hope to release this update as soon as possible
*/

-- ALTER TABLE "${tableName}" DROP CONSTRAINT "<constraint_name>";`;
      }
    };
    PgAlterTableAlterColumnSetNotNullConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_set_notnull" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" SET NOT NULL;`;
      }
    };
    PgAlterTableAlterColumnDropNotNullConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_alter_column_drop_notnull" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, columnName } = statement;
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN "${columnName}" DROP NOT NULL;`;
      }
    };
    PgCreateForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_reference" && dialect6 === "postgresql";
      }
      convert(statement) {
        const {
          name: name2,
          tableFrom,
          tableTo,
          columnsFrom,
          columnsTo,
          onDelete,
          onUpdate,
          schemaTo
        } = PgSquasher.unsquashFK(statement.data);
        const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
        const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
        const fromColumnsString = columnsFrom.map((it) => `"${it}"`).join(",");
        const toColumnsString = columnsTo.map((it) => `"${it}"`).join(",");
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${tableFrom}"` : `"${tableFrom}"`;
        const tableToNameWithSchema = schemaTo ? `"${schemaTo}"."${tableTo}"` : `"${tableTo}"`;
        const alterStatement = `ALTER TABLE ${tableNameWithSchema} ADD CONSTRAINT "${name2}" FOREIGN KEY (${fromColumnsString}) REFERENCES ${tableToNameWithSchema}(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`;
        return alterStatement;
      }
    };
    LibSQLCreateForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_reference" && dialect6 === "turso";
      }
      convert(statement, json22, action) {
        const { columnsFrom, columnsTo, tableFrom, onDelete, onUpdate, tableTo } = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
        const { columnDefault, columnNotNull, columnType } = statement;
        const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
        const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
        const columnsDefaultValue = columnDefault ? ` DEFAULT ${columnDefault}` : "";
        const columnNotNullValue = columnNotNull ? ` NOT NULL` : "";
        const columnTypeValue = columnType ? ` ${columnType}` : "";
        const columnFrom = columnsFrom[0];
        const columnTo = columnsTo[0];
        return `ALTER TABLE \`${tableFrom}\` ALTER COLUMN "${columnFrom}" TO "${columnFrom}"${columnTypeValue}${columnNotNullValue}${columnsDefaultValue} REFERENCES ${tableTo}(${columnTo})${onDeleteStatement}${onUpdateStatement};`;
      }
    };
    MySqlCreateForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_reference" && dialect6 === "mysql";
      }
      convert(statement) {
        const {
          name: name2,
          tableFrom,
          tableTo,
          columnsFrom,
          columnsTo,
          onDelete,
          onUpdate
        } = MySqlSquasher.unsquashFK(statement.data);
        const onDeleteStatement = onDelete ? ` ON DELETE ${onDelete}` : "";
        const onUpdateStatement = onUpdate ? ` ON UPDATE ${onUpdate}` : "";
        const fromColumnsString = columnsFrom.map((it) => `\`${it}\``).join(",");
        const toColumnsString = columnsTo.map((it) => `\`${it}\``).join(",");
        return `ALTER TABLE \`${tableFrom}\` ADD CONSTRAINT \`${name2}\` FOREIGN KEY (${fromColumnsString}) REFERENCES \`${tableTo}\`(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`;
      }
    };
    PgAlterForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_reference" && dialect6 === "postgresql";
      }
      convert(statement) {
        const newFk = PgSquasher.unsquashFK(statement.data);
        const oldFk = PgSquasher.unsquashFK(statement.oldFkey);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${oldFk.tableFrom}"` : `"${oldFk.tableFrom}"`;
        let sql2 = `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${oldFk.name}";
`;
        const onDeleteStatement = newFk.onDelete ? ` ON DELETE ${newFk.onDelete}` : "";
        const onUpdateStatement = newFk.onUpdate ? ` ON UPDATE ${newFk.onUpdate}` : "";
        const fromColumnsString = newFk.columnsFrom.map((it) => `"${it}"`).join(",");
        const toColumnsString = newFk.columnsTo.map((it) => `"${it}"`).join(",");
        const tableFromNameWithSchema = oldFk.schemaTo ? `"${oldFk.schemaTo}"."${oldFk.tableFrom}"` : `"${oldFk.tableFrom}"`;
        const tableToNameWithSchema = newFk.schemaTo ? `"${newFk.schemaTo}"."${newFk.tableFrom}"` : `"${newFk.tableFrom}"`;
        const alterStatement = `ALTER TABLE ${tableFromNameWithSchema} ADD CONSTRAINT "${newFk.name}" FOREIGN KEY (${fromColumnsString}) REFERENCES ${tableToNameWithSchema}(${toColumnsString})${onDeleteStatement}${onUpdateStatement};`;
        sql2 += alterStatement;
        return sql2;
      }
    };
    PgDeleteForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_reference" && dialect6 === "postgresql";
      }
      convert(statement) {
        const tableFrom = statement.tableName;
        const { name: name2 } = PgSquasher.unsquashFK(statement.data);
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${tableFrom}"` : `"${tableFrom}"`;
        return `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${name2}";
`;
      }
    };
    MySqlDeleteForeignKeyConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "delete_reference" && dialect6 === "mysql";
      }
      convert(statement) {
        const tableFrom = statement.tableName;
        const { name: name2 } = MySqlSquasher.unsquashFK(statement.data);
        return `ALTER TABLE \`${tableFrom}\` DROP FOREIGN KEY \`${name2}\`;
`;
      }
    };
    CreatePgIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_index_pg" && dialect6 === "postgresql";
      }
      convert(statement) {
        const {
          name: name2,
          columns,
          isUnique,
          concurrently,
          with: withMap,
          method,
          where
        } = statement.data;
        const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
        const value = columns.map(
          (it) => `${it.isExpression ? it.expression : `"${it.expression}"`}${it.opclass ? ` ${it.opclass}` : it.asc ? "" : " DESC"}${it.asc && it.nulls && it.nulls === "last" || it.opclass ? "" : ` NULLS ${it.nulls.toUpperCase()}`}`
        ).join(",");
        const tableNameWithSchema = statement.schema ? `"${statement.schema}"."${statement.tableName}"` : `"${statement.tableName}"`;
        function reverseLogic(mappedWith) {
          let reversedString = "";
          for (const key in mappedWith) {
            if (mappedWith.hasOwnProperty(key)) {
              reversedString += `${key}=${mappedWith[key]},`;
            }
          }
          reversedString = reversedString.slice(0, -1);
          return reversedString;
        }
        return `CREATE ${indexPart}${concurrently ? " CONCURRENTLY" : ""} "${name2}" ON ${tableNameWithSchema} USING ${method} (${value})${Object.keys(withMap).length !== 0 ? ` WITH (${reverseLogic(withMap)})` : ""}${where ? ` WHERE ${where}` : ""};`;
      }
    };
    CreateMySqlIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_index" && dialect6 === "mysql";
      }
      convert(statement) {
        const { name: name2, columns, isUnique } = MySqlSquasher.unsquashIdx(
          statement.data
        );
        const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
        const uniqueString = columns.map((it) => {
          return statement.internal?.indexes ? statement.internal?.indexes[name2]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
        }).join(",");
        return `CREATE ${indexPart} \`${name2}\` ON \`${statement.tableName}\` (${uniqueString});`;
      }
    };
    CreateSingleStoreIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_index" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { name: name2, columns, isUnique } = SingleStoreSquasher.unsquashIdx(
          statement.data
        );
        const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
        const uniqueString = columns.map((it) => {
          return statement.internal?.indexes ? statement.internal?.indexes[name2]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
        }).join(",");
        return `CREATE ${indexPart} \`${name2}\` ON \`${statement.tableName}\` (${uniqueString});`;
      }
    };
    CreateSqliteIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_index" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { name: name2, columns, isUnique, where } = SQLiteSquasher.unsquashIdx(
          statement.data
        );
        const indexPart = isUnique ? "UNIQUE INDEX" : "INDEX";
        const whereStatement = where ? ` WHERE ${where}` : "";
        const uniqueString = columns.map((it) => {
          return statement.internal?.indexes ? statement.internal?.indexes[name2]?.columns[it]?.isExpression ? it : `\`${it}\`` : `\`${it}\``;
        }).join(",");
        return `CREATE ${indexPart} \`${name2}\` ON \`${statement.tableName}\` (${uniqueString})${whereStatement};`;
      }
    };
    PgDropIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_index" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { schema: schema5 } = statement;
        const { name: name2 } = PgSquasher.unsquashIdx(statement.data);
        const indexNameWithSchema = schema5 ? `"${schema5}"."${name2}"` : `"${name2}"`;
        return `DROP INDEX ${indexNameWithSchema};`;
      }
    };
    PgCreateSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "create_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { name: name2 } = statement;
        return `CREATE SCHEMA "${name2}";
`;
      }
    };
    PgRenameSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "rename_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { from, to } = statement;
        return `ALTER SCHEMA "${from}" RENAME TO "${to}";
`;
      }
    };
    PgDropSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { name: name2 } = statement;
        return `DROP SCHEMA "${name2}";
`;
      }
    };
    PgAlterTableSetSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_set_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, schemaFrom, schemaTo } = statement;
        return `ALTER TABLE "${schemaFrom}"."${tableName}" SET SCHEMA "${schemaTo}";
`;
      }
    };
    PgAlterTableSetNewSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_set_new_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, to, from } = statement;
        const tableNameWithSchema = from ? `"${from}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} SET SCHEMA "${to}";
`;
      }
    };
    PgAlterTableRemoveFromSchemaConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "alter_table_remove_from_schema" && dialect6 === "postgresql";
      }
      convert(statement) {
        const { tableName, schema: schema5 } = statement;
        const tableNameWithSchema = schema5 ? `"${schema5}"."${tableName}"` : `"${tableName}"`;
        return `ALTER TABLE ${tableNameWithSchema} SET SCHEMA public;
`;
      }
    };
    SqliteDropIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_index" && (dialect6 === "sqlite" || dialect6 === "turso");
      }
      convert(statement) {
        const { name: name2 } = PgSquasher.unsquashIdx(statement.data);
        return `DROP INDEX \`${name2}\`;`;
      }
    };
    MySqlDropIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_index" && dialect6 === "mysql";
      }
      convert(statement) {
        const { name: name2 } = MySqlSquasher.unsquashIdx(statement.data);
        return `DROP INDEX \`${name2}\` ON \`${statement.tableName}\`;`;
      }
    };
    SingleStoreDropIndexConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "drop_index" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { name: name2 } = SingleStoreSquasher.unsquashIdx(statement.data);
        return `DROP INDEX \`${name2}\` ON \`${statement.tableName}\`;`;
      }
    };
    SQLiteRecreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "recreate_table" && dialect6 === "sqlite";
      }
      convert(statement) {
        const { tableName, columns, compositePKs, referenceData, checkConstraints } = statement;
        const columnNames = columns.map((it) => `"${it.name}"`).join(", ");
        const newTableName = `__new_${tableName}`;
        const sqlStatements = [];
        sqlStatements.push(`PRAGMA foreign_keys=OFF;`);
        const mappedCheckConstraints = checkConstraints.map(
          (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `'${newTableName}'.`)
        );
        sqlStatements.push(
          new SQLiteCreateTableConvertor().convert({
            type: "sqlite_create_table",
            tableName: newTableName,
            columns,
            referenceData,
            compositePKs,
            checkConstraints: mappedCheckConstraints
          })
        );
        sqlStatements.push(
          `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;`
        );
        sqlStatements.push(
          new SQLiteDropTableConvertor().convert({
            type: "drop_table",
            tableName,
            schema: ""
          })
        );
        sqlStatements.push(
          new SqliteRenameTableConvertor().convert({
            fromSchema: "",
            tableNameFrom: newTableName,
            tableNameTo: tableName,
            toSchema: "",
            type: "rename_table"
          })
        );
        sqlStatements.push(`PRAGMA foreign_keys=ON;`);
        return sqlStatements;
      }
    };
    LibSQLRecreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "recreate_table" && dialect6 === "turso";
      }
      convert(statement) {
        const { tableName, columns, compositePKs, referenceData, checkConstraints } = statement;
        const columnNames = columns.map((it) => `"${it.name}"`).join(", ");
        const newTableName = `__new_${tableName}`;
        const sqlStatements = [];
        const mappedCheckConstraints = checkConstraints.map(
          (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
        );
        sqlStatements.push(`PRAGMA foreign_keys=OFF;`);
        sqlStatements.push(
          new SQLiteCreateTableConvertor().convert({
            type: "sqlite_create_table",
            tableName: newTableName,
            columns,
            referenceData,
            compositePKs,
            checkConstraints: mappedCheckConstraints
          })
        );
        sqlStatements.push(
          `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;`
        );
        sqlStatements.push(
          new SQLiteDropTableConvertor().convert({
            type: "drop_table",
            tableName,
            schema: ""
          })
        );
        sqlStatements.push(
          new SqliteRenameTableConvertor().convert({
            fromSchema: "",
            tableNameFrom: newTableName,
            tableNameTo: tableName,
            toSchema: "",
            type: "rename_table"
          })
        );
        sqlStatements.push(`PRAGMA foreign_keys=ON;`);
        return sqlStatements;
      }
    };
    SingleStoreRecreateTableConvertor = class extends Convertor {
      can(statement, dialect6) {
        return statement.type === "singlestore_recreate_table" && dialect6 === "singlestore";
      }
      convert(statement) {
        const { tableName, columns, compositePKs, uniqueConstraints } = statement;
        const columnNames = columns.map((it) => `\`${it.name}\``).join(", ");
        const newTableName = `__new_${tableName}`;
        const sqlStatements = [];
        sqlStatements.push(
          new SingleStoreCreateTableConvertor().convert({
            type: "create_table",
            tableName: newTableName,
            columns,
            compositePKs,
            uniqueConstraints,
            schema: ""
          })
        );
        sqlStatements.push(
          `INSERT INTO \`${newTableName}\`(${columnNames}) SELECT ${columnNames} FROM \`${tableName}\`;`
        );
        sqlStatements.push(
          new SingleStoreDropTableConvertor().convert({
            type: "drop_table",
            tableName,
            schema: ""
          })
        );
        sqlStatements.push(
          new SingleStoreRenameTableConvertor().convert({
            fromSchema: "",
            tableNameFrom: newTableName,
            tableNameTo: tableName,
            toSchema: "",
            type: "rename_table"
          })
        );
        return sqlStatements;
      }
    };
    convertors = [];
    convertors.push(new PgCreateTableConvertor());
    convertors.push(new MySqlCreateTableConvertor());
    convertors.push(new SingleStoreCreateTableConvertor());
    convertors.push(new SingleStoreRecreateTableConvertor());
    convertors.push(new SQLiteCreateTableConvertor());
    convertors.push(new SQLiteRecreateTableConvertor());
    convertors.push(new LibSQLRecreateTableConvertor());
    convertors.push(new PgCreateViewConvertor());
    convertors.push(new PgDropViewConvertor());
    convertors.push(new PgRenameViewConvertor());
    convertors.push(new PgAlterViewSchemaConvertor());
    convertors.push(new PgAlterViewAddWithOptionConvertor());
    convertors.push(new PgAlterViewDropWithOptionConvertor());
    convertors.push(new PgAlterViewAlterTablespaceConvertor());
    convertors.push(new PgAlterViewAlterUsingConvertor());
    convertors.push(new MySqlCreateViewConvertor());
    convertors.push(new MySqlDropViewConvertor());
    convertors.push(new MySqlRenameViewConvertor());
    convertors.push(new MySqlAlterViewConvertor());
    convertors.push(new SqliteCreateViewConvertor());
    convertors.push(new SqliteDropViewConvertor());
    convertors.push(new CreateTypeEnumConvertor());
    convertors.push(new DropTypeEnumConvertor());
    convertors.push(new AlterTypeAddValueConvertor());
    convertors.push(new AlterTypeSetSchemaConvertor());
    convertors.push(new AlterRenameTypeConvertor());
    convertors.push(new AlterTypeDropValueConvertor());
    convertors.push(new CreatePgSequenceConvertor());
    convertors.push(new DropPgSequenceConvertor());
    convertors.push(new RenamePgSequenceConvertor());
    convertors.push(new MovePgSequenceConvertor());
    convertors.push(new AlterPgSequenceConvertor());
    convertors.push(new PgDropTableConvertor());
    convertors.push(new MySQLDropTableConvertor());
    convertors.push(new SingleStoreDropTableConvertor());
    convertors.push(new SQLiteDropTableConvertor());
    convertors.push(new PgRenameTableConvertor());
    convertors.push(new MySqlRenameTableConvertor());
    convertors.push(new SingleStoreRenameTableConvertor());
    convertors.push(new SqliteRenameTableConvertor());
    convertors.push(new PgAlterTableRenameColumnConvertor());
    convertors.push(new MySqlAlterTableRenameColumnConvertor());
    convertors.push(new SingleStoreAlterTableRenameColumnConvertor());
    convertors.push(new SQLiteAlterTableRenameColumnConvertor());
    convertors.push(new PgAlterTableDropColumnConvertor());
    convertors.push(new MySqlAlterTableDropColumnConvertor());
    convertors.push(new SingleStoreAlterTableDropColumnConvertor());
    convertors.push(new SQLiteAlterTableDropColumnConvertor());
    convertors.push(new PgAlterTableAddColumnConvertor());
    convertors.push(new MySqlAlterTableAddColumnConvertor());
    convertors.push(new SingleStoreAlterTableAddColumnConvertor());
    convertors.push(new SQLiteAlterTableAddColumnConvertor());
    convertors.push(new PgAlterTableAlterColumnSetTypeConvertor());
    convertors.push(new PgAlterTableAddUniqueConstraintConvertor());
    convertors.push(new PgAlterTableDropUniqueConstraintConvertor());
    convertors.push(new PgAlterTableAddCheckConstraintConvertor());
    convertors.push(new PgAlterTableDeleteCheckConstraintConvertor());
    convertors.push(new MySqlAlterTableAddCheckConstraintConvertor());
    convertors.push(new MySqlAlterTableDeleteCheckConstraintConvertor());
    convertors.push(new MySQLAlterTableAddUniqueConstraintConvertor());
    convertors.push(new MySQLAlterTableDropUniqueConstraintConvertor());
    convertors.push(new SingleStoreAlterTableAddUniqueConstraintConvertor());
    convertors.push(new SingleStoreAlterTableDropUniqueConstraintConvertor());
    convertors.push(new CreatePgIndexConvertor());
    convertors.push(new CreateMySqlIndexConvertor());
    convertors.push(new CreateSingleStoreIndexConvertor());
    convertors.push(new CreateSqliteIndexConvertor());
    convertors.push(new PgDropIndexConvertor());
    convertors.push(new SqliteDropIndexConvertor());
    convertors.push(new MySqlDropIndexConvertor());
    convertors.push(new SingleStoreDropIndexConvertor());
    convertors.push(new PgAlterTableAlterColumnSetPrimaryKeyConvertor());
    convertors.push(new PgAlterTableAlterColumnDropPrimaryKeyConvertor());
    convertors.push(new PgAlterTableAlterColumnSetNotNullConvertor());
    convertors.push(new PgAlterTableAlterColumnDropNotNullConvertor());
    convertors.push(new PgAlterTableAlterColumnSetDefaultConvertor());
    convertors.push(new PgAlterTableAlterColumnDropDefaultConvertor());
    convertors.push(new PgAlterPolicyConvertor());
    convertors.push(new PgCreatePolicyConvertor());
    convertors.push(new PgDropPolicyConvertor());
    convertors.push(new PgRenamePolicyConvertor());
    convertors.push(new PgAlterIndPolicyConvertor());
    convertors.push(new PgCreateIndPolicyConvertor());
    convertors.push(new PgDropIndPolicyConvertor());
    convertors.push(new PgRenameIndPolicyConvertor());
    convertors.push(new PgEnableRlsConvertor());
    convertors.push(new PgDisableRlsConvertor());
    convertors.push(new PgDropRoleConvertor());
    convertors.push(new PgAlterRoleConvertor());
    convertors.push(new PgCreateRoleConvertor());
    convertors.push(new PgRenameRoleConvertor());
    convertors.push(new PgAlterTableAlterColumnSetExpressionConvertor());
    convertors.push(new PgAlterTableAlterColumnDropGeneratedConvertor());
    convertors.push(new PgAlterTableAlterColumnAlterrGeneratedConvertor());
    convertors.push(new MySqlAlterTableAlterColumnAlterrGeneratedConvertor());
    convertors.push(new SingleStoreAlterTableAlterColumnAlterrGeneratedConvertor());
    convertors.push(new SqliteAlterTableAlterColumnDropGeneratedConvertor());
    convertors.push(new SqliteAlterTableAlterColumnAlterGeneratedConvertor());
    convertors.push(new SqliteAlterTableAlterColumnSetExpressionConvertor());
    convertors.push(new MySqlModifyColumn());
    convertors.push(new LibSQLModifyColumn());
    convertors.push(new SingleStoreModifyColumn());
    convertors.push(new PgCreateForeignKeyConvertor());
    convertors.push(new MySqlCreateForeignKeyConvertor());
    convertors.push(new PgAlterForeignKeyConvertor());
    convertors.push(new PgDeleteForeignKeyConvertor());
    convertors.push(new MySqlDeleteForeignKeyConvertor());
    convertors.push(new PgCreateSchemaConvertor());
    convertors.push(new PgRenameSchemaConvertor());
    convertors.push(new PgDropSchemaConvertor());
    convertors.push(new PgAlterTableSetSchemaConvertor());
    convertors.push(new PgAlterTableSetNewSchemaConvertor());
    convertors.push(new PgAlterTableRemoveFromSchemaConvertor());
    convertors.push(new LibSQLCreateForeignKeyConvertor());
    convertors.push(new PgAlterTableAlterColumnDropGenerated());
    convertors.push(new PgAlterTableAlterColumnSetGenerated());
    convertors.push(new PgAlterTableAlterColumnAlterGenerated());
    convertors.push(new PgAlterTableCreateCompositePrimaryKeyConvertor());
    convertors.push(new PgAlterTableDeleteCompositePrimaryKeyConvertor());
    convertors.push(new PgAlterTableAlterCompositePrimaryKeyConvertor());
    convertors.push(new MySqlAlterTableDeleteCompositePrimaryKeyConvertor());
    convertors.push(new MySqlAlterTableDropPk());
    convertors.push(new MySqlAlterTableCreateCompositePrimaryKeyConvertor());
    convertors.push(new MySqlAlterTableAddPk());
    convertors.push(new MySqlAlterTableAlterCompositePrimaryKeyConvertor());
    convertors.push(new SingleStoreAlterTableDropPk());
    convertors.push(new SingleStoreAlterTableAddPk());
    https: `
create table users (
	id int,
    name character varying(128)
);

create type venum as enum('one', 'two', 'three');
alter table users add column typed venum;

insert into users(id, name, typed) values (1, 'name1', 'one');
insert into users(id, name, typed) values (2, 'name2', 'two');
insert into users(id, name, typed) values (3, 'name3', 'three');

alter type venum rename to __venum;
create type venum as enum ('one', 'two', 'three', 'four', 'five');

ALTER TABLE users ALTER COLUMN typed TYPE venum USING typed::text::venum;

insert into users(id, name, typed) values (4, 'name4', 'four');
insert into users(id, name, typed) values (5, 'name5', 'five');

drop type __venum;
`;
  }
});

// src/cli/commands/sqlitePushUtils.ts
var _moveDataStatements, getOldTableName, getNewTableName, logSuggestionsAndReturn;
var init_sqlitePushUtils = __esm({
  "src/cli/commands/sqlitePushUtils.ts"() {
    "use strict";
    init_source();
    init_sqliteSchema();
    init_sqlgenerator();
    init_utils();
    _moveDataStatements = (tableName, json4, dataLoss = false) => {
      const statements = [];
      const newTableName = `__new_${tableName}`;
      const tableColumns = Object.values(json4.tables[tableName].columns);
      const referenceData = Object.values(json4.tables[tableName].foreignKeys);
      const compositePKs = Object.values(
        json4.tables[tableName].compositePrimaryKeys
      ).map((it) => SQLiteSquasher.unsquashPK(it));
      const checkConstraints = Object.values(json4.tables[tableName].checkConstraints);
      const mappedCheckConstraints = checkConstraints.map(
        (it) => it.replaceAll(`"${tableName}".`, `"${newTableName}".`).replaceAll(`\`${tableName}\`.`, `\`${newTableName}\`.`).replaceAll(`${tableName}.`, `${newTableName}.`).replaceAll(`'${tableName}'.`, `\`${newTableName}\`.`)
      );
      const fks = referenceData.map((it) => SQLiteSquasher.unsquashPushFK(it));
      statements.push(
        new SQLiteCreateTableConvertor().convert({
          type: "sqlite_create_table",
          tableName: newTableName,
          columns: tableColumns,
          referenceData: fks,
          compositePKs,
          checkConstraints: mappedCheckConstraints
        })
      );
      if (!dataLoss) {
        const columns = Object.keys(json4.tables[tableName].columns).map(
          (c) => `"${c}"`
        );
        statements.push(
          `INSERT INTO \`${newTableName}\`(${columns.join(
            ", "
          )}) SELECT ${columns.join(", ")} FROM \`${tableName}\`;`
        );
      }
      statements.push(
        new SQLiteDropTableConvertor().convert({
          type: "drop_table",
          tableName,
          schema: ""
        })
      );
      statements.push(
        new SqliteRenameTableConvertor().convert({
          fromSchema: "",
          tableNameFrom: newTableName,
          tableNameTo: tableName,
          toSchema: "",
          type: "rename_table"
        })
      );
      for (const idx of Object.values(json4.tables[tableName].indexes)) {
        statements.push(
          new CreateSqliteIndexConvertor().convert({
            type: "create_index",
            tableName,
            schema: "",
            data: idx
          })
        );
      }
      return statements;
    };
    getOldTableName = (tableName, meta) => {
      for (const key of Object.keys(meta.tables)) {
        const value = meta.tables[key];
        if (`"${tableName}"` === value) {
          return key.substring(1, key.length - 1);
        }
      }
      return tableName;
    };
    getNewTableName = (tableName, meta) => {
      if (typeof meta.tables[`"${tableName}"`] !== "undefined") {
        return meta.tables[`"${tableName}"`].substring(
          1,
          meta.tables[`"${tableName}"`].length - 1
        );
      }
      return tableName;
    };
    logSuggestionsAndReturn = async (connection, statements, json1, json22, meta) => {
      let shouldAskForApprove = false;
      const statementsToExecute = [];
      const infoToPrint = [];
      const tablesToRemove = [];
      const columnsToRemove = [];
      const schemasToRemove = [];
      const tablesToTruncate = [];
      for (const statement of statements) {
        if (statement.type === "drop_table") {
          const res = await connection.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count2 = Number(res[0].count);
          if (count2 > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.tableName
              )} table with ${count2} items`
            );
            tablesToRemove.push(statement.tableName);
            shouldAskForApprove = true;
          }
          const fromJsonStatement = fromJson([statement], "sqlite", "push");
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        } else if (statement.type === "alter_table_drop_column") {
          const tableName = statement.tableName;
          const columnName = statement.columnName;
          const res = await connection.query(
            `select count(\`${tableName}\`.\`${columnName}\`) as count from \`${tableName}\``
          );
          const count2 = Number(res[0].count);
          if (count2 > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                columnName
              )} column in ${tableName} table with ${count2} items`
            );
            columnsToRemove.push(`${tableName}_${statement.columnName}`);
            shouldAskForApprove = true;
          }
          const fromJsonStatement = fromJson([statement], "sqlite", "push");
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        } else if (statement.type === "sqlite_alter_table_add_column" && (statement.column.notNull && !statement.column.default)) {
          const tableName = statement.tableName;
          const columnName = statement.column.name;
          const res = await connection.query(
            `select count(*) as count from \`${tableName}\``
          );
          const count2 = Number(res[0].count);
          if (count2 > 0) {
            infoToPrint.push(
              `\xB7 You're about to add not-null ${source_default.underline(
                columnName
              )} column without default value, which contains ${count2} items`
            );
            tablesToTruncate.push(tableName);
            statementsToExecute.push(`delete from ${tableName};`);
            shouldAskForApprove = true;
          }
          const fromJsonStatement = fromJson([statement], "sqlite", "push");
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        } else if (statement.type === "recreate_table") {
          const tableName = statement.tableName;
          const oldTableName = getOldTableName(tableName, meta);
          let dataLoss = false;
          const prevColumnNames = Object.keys(json1.tables[oldTableName].columns);
          const currentColumnNames = Object.keys(json22.tables[tableName].columns);
          const { removedColumns, addedColumns } = findAddedAndRemoved(
            prevColumnNames,
            currentColumnNames
          );
          if (removedColumns.length) {
            for (const removedColumn of removedColumns) {
              const res = await connection.query(
                `select count(\`${tableName}\`.\`${removedColumn}\`) as count from \`${tableName}\``
              );
              const count2 = Number(res[0].count);
              if (count2 > 0) {
                infoToPrint.push(
                  `\xB7 You're about to delete ${source_default.underline(
                    removedColumn
                  )} column in ${tableName} table with ${count2} items`
                );
                columnsToRemove.push(removedColumn);
                shouldAskForApprove = true;
              }
            }
          }
          if (addedColumns.length) {
            for (const addedColumn of addedColumns) {
              const [res] = await connection.query(
                `select count(*) as count from \`${tableName}\``
              );
              const columnConf = json22.tables[tableName].columns[addedColumn];
              const count2 = Number(res.count);
              if (count2 > 0 && columnConf.notNull && !columnConf.default) {
                dataLoss = true;
                infoToPrint.push(
                  `\xB7 You're about to add not-null ${source_default.underline(
                    addedColumn
                  )} column without default value to table, which contains ${count2} items`
                );
                shouldAskForApprove = true;
                tablesToTruncate.push(tableName);
                statementsToExecute.push(`DELETE FROM \`${tableName}\`;`);
              }
            }
          }
          const tablesReferencingCurrent = [];
          for (const table6 of Object.values(json22.tables)) {
            const tablesRefs = Object.values(json22.tables[table6.name].foreignKeys).filter((t) => SQLiteSquasher.unsquashPushFK(t).tableTo === tableName).map((it) => SQLiteSquasher.unsquashPushFK(it).tableFrom);
            tablesReferencingCurrent.push(...tablesRefs);
          }
          if (!tablesReferencingCurrent.length) {
            statementsToExecute.push(..._moveDataStatements(tableName, json22, dataLoss));
            continue;
          }
          const [{ foreign_keys: pragmaState }] = await connection.query(`PRAGMA foreign_keys;`);
          if (pragmaState) {
            statementsToExecute.push(`PRAGMA foreign_keys=OFF;`);
          }
          statementsToExecute.push(..._moveDataStatements(tableName, json22, dataLoss));
          if (pragmaState) {
            statementsToExecute.push(`PRAGMA foreign_keys=ON;`);
          }
        } else {
          const fromJsonStatement = fromJson([statement], "sqlite", "push");
          statementsToExecute.push(
            ...Array.isArray(fromJsonStatement) ? fromJsonStatement : [fromJsonStatement]
          );
        }
      }
      return {
        statementsToExecute,
        shouldAskForApprove,
        infoToPrint,
        columnsToRemove: [...new Set(columnsToRemove)],
        schemasToRemove: [...new Set(schemasToRemove)],
        tablesToTruncate: [...new Set(tablesToTruncate)],
        tablesToRemove: [...new Set(tablesToRemove)]
      };
    };
  }
});

// src/jsonStatements.ts
var preparePgCreateTableJson, prepareMySqlCreateTableJson, prepareSingleStoreCreateTableJson, prepareSQLiteCreateTable, prepareDropTableJson, prepareRenameTableJson, prepareCreateEnumJson, prepareAddValuesToEnumJson, prepareDropEnumValues, prepareDropEnumJson, prepareMoveEnumJson, prepareRenameEnumJson, prepareCreateSequenceJson, prepareAlterSequenceJson, prepareDropSequenceJson, prepareMoveSequenceJson, prepareRenameSequenceJson, prepareCreateRoleJson, prepareAlterRoleJson, prepareDropRoleJson, prepareRenameRoleJson, prepareCreateSchemasJson, prepareRenameSchemasJson, prepareDeleteSchemasJson, prepareRenameColumns, _prepareDropColumns, _prepareAddColumns, _prepareSqliteAddColumns, prepareAlterColumnsMysql, preparePgAlterColumns, prepareSqliteAlterColumns, prepareRenamePolicyJsons, prepareRenameIndPolicyJsons, prepareCreatePolicyJsons, prepareCreateIndPolicyJsons, prepareDropPolicyJsons, prepareDropIndPolicyJsons, prepareAlterPolicyJson, prepareAlterIndPolicyJson, preparePgCreateIndexesJson, prepareCreateIndexesJson, prepareCreateReferencesJson, prepareLibSQLCreateReferencesJson, prepareDropReferencesJson, prepareLibSQLDropReferencesJson, prepareAlterReferencesJson, prepareDropIndexesJson, prepareAddCompositePrimaryKeySqlite, prepareDeleteCompositePrimaryKeySqlite, prepareAlterCompositePrimaryKeySqlite, prepareAddCompositePrimaryKeyPg, prepareDeleteCompositePrimaryKeyPg, prepareAlterCompositePrimaryKeyPg, prepareAddUniqueConstraintPg, prepareDeleteUniqueConstraintPg, prepareAddCheckConstraint, prepareDeleteCheckConstraint, prepareAddCompositePrimaryKeyMySql, prepareDeleteCompositePrimaryKeyMySql, prepareAlterCompositePrimaryKeyMySql, preparePgCreateViewJson, prepareMySqlCreateViewJson, prepareSqliteCreateViewJson, prepareDropViewJson, prepareRenameViewJson, preparePgAlterViewAlterSchemaJson, preparePgAlterViewAddWithOptionJson, preparePgAlterViewDropWithOptionJson, preparePgAlterViewAlterTablespaceJson, preparePgAlterViewAlterUsingJson, prepareMySqlAlterView;
var init_jsonStatements = __esm({
  "src/jsonStatements.ts"() {
    "use strict";
    init_source();
    init_sqlitePushUtils();
    init_views();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    preparePgCreateTableJson = (table6, json22) => {
      const { name: name2, schema: schema5, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints, policies, isRLSEnabled } = table6;
      const tableKey2 = `${schema5 || "public"}.${name2}`;
      const compositePkName = Object.values(compositePrimaryKeys).length > 0 ? json22.tables[tableKey2].compositePrimaryKeys[`${PgSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name}`].name : "";
      return {
        type: "create_table",
        tableName: name2,
        schema: schema5,
        columns: Object.values(columns),
        compositePKs: Object.values(compositePrimaryKeys),
        compositePkName,
        uniqueConstraints: Object.values(uniqueConstraints),
        policies: Object.values(policies),
        checkConstraints: Object.values(checkConstraints),
        isRLSEnabled: isRLSEnabled ?? false
      };
    };
    prepareMySqlCreateTableJson = (table6, json22, internals) => {
      const { name: name2, schema: schema5, columns, compositePrimaryKeys, uniqueConstraints, checkConstraints } = table6;
      return {
        type: "create_table",
        tableName: name2,
        schema: schema5,
        columns: Object.values(columns),
        compositePKs: Object.values(compositePrimaryKeys),
        compositePkName: Object.values(compositePrimaryKeys).length > 0 ? json22.tables[name2].compositePrimaryKeys[MySqlSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name].name : "",
        uniqueConstraints: Object.values(uniqueConstraints),
        internals,
        checkConstraints: Object.values(checkConstraints)
      };
    };
    prepareSingleStoreCreateTableJson = (table6, json22, internals) => {
      const { name: name2, schema: schema5, columns, compositePrimaryKeys, uniqueConstraints } = table6;
      return {
        type: "create_table",
        tableName: name2,
        schema: schema5,
        columns: Object.values(columns),
        compositePKs: Object.values(compositePrimaryKeys),
        compositePkName: Object.values(compositePrimaryKeys).length > 0 ? json22.tables[name2].compositePrimaryKeys[SingleStoreSquasher.unsquashPK(Object.values(compositePrimaryKeys)[0]).name].name : "",
        uniqueConstraints: Object.values(uniqueConstraints),
        internals
      };
    };
    prepareSQLiteCreateTable = (table6, action) => {
      const { name: name2, columns, uniqueConstraints, checkConstraints } = table6;
      const references2 = Object.values(table6.foreignKeys);
      const composites = Object.values(table6.compositePrimaryKeys).map(
        (it) => SQLiteSquasher.unsquashPK(it)
      );
      const fks = references2.map(
        (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it)
      );
      return {
        type: "sqlite_create_table",
        tableName: name2,
        columns: Object.values(columns),
        referenceData: fks,
        compositePKs: composites,
        uniqueConstraints: Object.values(uniqueConstraints),
        checkConstraints: Object.values(checkConstraints)
      };
    };
    prepareDropTableJson = (table6) => {
      return {
        type: "drop_table",
        tableName: table6.name,
        schema: table6.schema,
        policies: table6.policies ? Object.values(table6.policies) : []
      };
    };
    prepareRenameTableJson = (tableFrom, tableTo) => {
      return {
        type: "rename_table",
        fromSchema: tableTo.schema,
        toSchema: tableTo.schema,
        tableNameFrom: tableFrom.name,
        tableNameTo: tableTo.name
      };
    };
    prepareCreateEnumJson = (name2, schema5, values) => {
      return {
        type: "create_type_enum",
        name: name2,
        schema: schema5,
        values
      };
    };
    prepareAddValuesToEnumJson = (name2, schema5, values) => {
      return values.map((it) => {
        return {
          type: "alter_type_add_value",
          name: name2,
          schema: schema5,
          value: it.value,
          before: it.before
        };
      });
    };
    prepareDropEnumValues = (name2, schema5, removedValues, json22) => {
      if (!removedValues.length) return [];
      const affectedColumns = [];
      for (const tableKey2 in json22.tables) {
        const table6 = json22.tables[tableKey2];
        for (const columnKey in table6.columns) {
          const column6 = table6.columns[columnKey];
          const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g;
          const parsedColumnType = column6.type.replace(arrayDefinitionRegex, "");
          if (parsedColumnType === name2 && column6.typeSchema === schema5) {
            affectedColumns.push({
              tableSchema: table6.schema,
              table: table6.name,
              column: column6.name,
              columnType: column6.type,
              default: column6.default
            });
          }
        }
      }
      return [{
        type: "alter_type_drop_value",
        name: name2,
        enumSchema: schema5,
        deletedValues: removedValues,
        newValues: json22.enums[`${schema5}.${name2}`].values,
        columnsWithEnum: affectedColumns
      }];
    };
    prepareDropEnumJson = (name2, schema5) => {
      return {
        type: "drop_type_enum",
        name: name2,
        schema: schema5
      };
    };
    prepareMoveEnumJson = (name2, schemaFrom, schemaTo) => {
      return {
        type: "move_type_enum",
        name: name2,
        schemaFrom,
        schemaTo
      };
    };
    prepareRenameEnumJson = (nameFrom, nameTo, schema5) => {
      return {
        type: "rename_type_enum",
        nameFrom,
        nameTo,
        schema: schema5
      };
    };
    prepareCreateSequenceJson = (seq) => {
      const values = PgSquasher.unsquashSequence(seq.values);
      return {
        type: "create_sequence",
        name: seq.name,
        schema: seq.schema,
        values
      };
    };
    prepareAlterSequenceJson = (seq) => {
      const values = PgSquasher.unsquashSequence(seq.values);
      return [
        {
          type: "alter_sequence",
          schema: seq.schema,
          name: seq.name,
          values
        }
      ];
    };
    prepareDropSequenceJson = (name2, schema5) => {
      return {
        type: "drop_sequence",
        name: name2,
        schema: schema5
      };
    };
    prepareMoveSequenceJson = (name2, schemaFrom, schemaTo) => {
      return {
        type: "move_sequence",
        name: name2,
        schemaFrom,
        schemaTo
      };
    };
    prepareRenameSequenceJson = (nameFrom, nameTo, schema5) => {
      return {
        type: "rename_sequence",
        nameFrom,
        nameTo,
        schema: schema5
      };
    };
    prepareCreateRoleJson = (role) => {
      return {
        type: "create_role",
        name: role.name,
        values: {
          createDb: role.createDb,
          createRole: role.createRole,
          inherit: role.inherit
        }
      };
    };
    prepareAlterRoleJson = (role) => {
      return {
        type: "alter_role",
        name: role.name,
        values: {
          createDb: role.createDb,
          createRole: role.createRole,
          inherit: role.inherit
        }
      };
    };
    prepareDropRoleJson = (name2) => {
      return {
        type: "drop_role",
        name: name2
      };
    };
    prepareRenameRoleJson = (nameFrom, nameTo) => {
      return {
        type: "rename_role",
        nameFrom,
        nameTo
      };
    };
    prepareCreateSchemasJson = (values) => {
      return values.map((it) => {
        return {
          type: "create_schema",
          name: it
        };
      });
    };
    prepareRenameSchemasJson = (values) => {
      return values.map((it) => {
        return {
          type: "rename_schema",
          from: it.from,
          to: it.to
        };
      });
    };
    prepareDeleteSchemasJson = (values) => {
      return values.map((it) => {
        return {
          type: "drop_schema",
          name: it
        };
      });
    };
    prepareRenameColumns = (tableName, schema5, pairs) => {
      return pairs.map((it) => {
        return {
          type: "alter_table_rename_column",
          tableName,
          oldColumnName: it.from.name,
          newColumnName: it.to.name,
          schema: schema5
        };
      });
    };
    _prepareDropColumns = (taleName, schema5, columns) => {
      return columns.map((it) => {
        return {
          type: "alter_table_drop_column",
          tableName: taleName,
          columnName: it.name,
          schema: schema5
        };
      });
    };
    _prepareAddColumns = (tableName, schema5, columns) => {
      return columns.map((it) => {
        return {
          type: "alter_table_add_column",
          tableName,
          column: it,
          schema: schema5
        };
      });
    };
    _prepareSqliteAddColumns = (tableName, columns, referenceData) => {
      const unsquashed = referenceData.map((addedFkValue) => SQLiteSquasher.unsquashFK(addedFkValue));
      return columns.map((it) => {
        const columnsWithReference = unsquashed.find((t) => t.columnsFrom.includes(it.name));
        if (it.generated?.type === "stored") {
          warning(
            `As SQLite docs mention: "It is not possible to ALTER TABLE ADD COLUMN a STORED column. One can add a VIRTUAL column, however", source: "https://www.sqlite.org/gencol.html"`
          );
          return void 0;
        }
        return {
          type: "sqlite_alter_table_add_column",
          tableName,
          column: it,
          referenceData: columnsWithReference ? SQLiteSquasher.squashFK(columnsWithReference) : void 0
        };
      }).filter(Boolean);
    };
    prepareAlterColumnsMysql = (tableName, schema5, columns, json1, json22, action) => {
      let statements = [];
      let dropPkStatements = [];
      let setPkStatements = [];
      for (const column6 of columns) {
        const columnName = typeof column6.name !== "string" ? column6.name.new : column6.name;
        const table6 = json22.tables[tableName];
        const snapshotColumn = table6.columns[columnName];
        const columnType = snapshotColumn.type;
        const columnDefault = snapshotColumn.default;
        const columnOnUpdate = "onUpdate" in snapshotColumn ? snapshotColumn.onUpdate : void 0;
        const columnNotNull = table6.columns[columnName].notNull;
        const columnAutoIncrement = "autoincrement" in snapshotColumn ? snapshotColumn.autoincrement ?? false : false;
        const columnPk = table6.columns[columnName].primaryKey;
        if (column6.autoincrement?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_autoincrement",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.autoincrement?.type === "changed") {
          const type = column6.autoincrement.new ? "alter_table_alter_column_set_autoincrement" : "alter_table_alter_column_drop_autoincrement";
          statements.push({
            type,
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.autoincrement?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_autoincrement",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
      }
      for (const column6 of columns) {
        const columnName = typeof column6.name !== "string" ? column6.name.new : column6.name;
        const columnType = json22.tables[tableName].columns[columnName].type;
        const columnDefault = json22.tables[tableName].columns[columnName].default;
        const columnGenerated = json22.tables[tableName].columns[columnName].generated;
        const columnOnUpdate = json22.tables[tableName].columns[columnName].onUpdate;
        const columnNotNull = json22.tables[tableName].columns[columnName].notNull;
        const columnAutoIncrement = json22.tables[tableName].columns[columnName].autoincrement;
        const columnPk = json22.tables[tableName].columns[columnName].primaryKey;
        const compositePk = json22.tables[tableName].compositePrimaryKeys[`${tableName}_${columnName}`];
        if (typeof column6.name !== "string") {
          statements.push({
            type: "alter_table_rename_column",
            tableName,
            oldColumnName: column6.name.old,
            newColumnName: column6.name.new,
            schema: schema5
          });
        }
        if (column6.type?.type === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_type",
            tableName,
            columnName,
            newDataType: column6.type.new,
            oldDataType: column6.type.old,
            schema: schema5,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (column6.primaryKey?.type === "deleted" || column6.primaryKey?.type === "changed" && !column6.primaryKey.new && typeof compositePk === "undefined") {
          dropPkStatements.push({
            ////
            type: "alter_table_alter_column_drop_pk",
            tableName,
            columnName,
            schema: schema5
          });
        }
        if (column6.default?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column6.default.value,
            schema: schema5,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.default?.type === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column6.default.new,
            oldDefaultValue: column6.default.old,
            schema: schema5,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.default?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_default",
            tableName,
            columnName,
            schema: schema5,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.notNull?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_notnull",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.notNull?.type === "changed") {
          const type = column6.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull";
          statements.push({
            type,
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.notNull?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_notnull",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.generated?.type === "added") {
          if (columnGenerated?.type === "virtual") {
            warning(
              `You are trying to add virtual generated constraint to ${source_default.blue(
                columnName
              )} column. As MySQL docs mention: "Nongenerated columns can be altered to stored but not virtual generated columns". We will drop an existing column and add it with a virtual generated statement. This means that the data previously stored in this column will be wiped, and new data will be generated on each read for this column
`
            );
          }
          statements.push({
            type: "alter_table_alter_column_set_generated",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (column6.generated?.type === "changed" && action !== "push") {
          statements.push({
            type: "alter_table_alter_column_alter_generated",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (column6.generated?.type === "deleted") {
          if (columnGenerated?.type === "virtual") {
            warning(
              `You are trying to remove virtual generated constraint from ${source_default.blue(
                columnName
              )} column. As MySQL docs mention: "Stored but not virtual generated columns can be altered to nongenerated columns. The stored generated values become the values of the nongenerated column". We will drop an existing column and add it without a virtual generated statement. This means that this column will have no data after migration
`
            );
          }
          statements.push({
            type: "alter_table_alter_column_drop_generated",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated,
            oldColumn: json1.tables[tableName].columns[columnName]
          });
        }
        if (column6.primaryKey?.type === "added" || column6.primaryKey?.type === "changed" && column6.primaryKey.new) {
          const wasAutoincrement = statements.filter(
            (it) => it.type === "alter_table_alter_column_set_autoincrement"
          );
          if (wasAutoincrement.length === 0) {
            setPkStatements.push({
              type: "alter_table_alter_column_set_pk",
              tableName,
              schema: schema5,
              columnName
            });
          }
        }
        if (column6.onUpdate?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_on_update",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.onUpdate?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_on_update",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
      }
      return [...dropPkStatements, ...setPkStatements, ...statements];
    };
    preparePgAlterColumns = (_tableName, schema5, columns, json22, json1, action) => {
      const tableKey2 = `${schema5 || "public"}.${_tableName}`;
      let statements = [];
      let dropPkStatements = [];
      let setPkStatements = [];
      for (const column6 of columns) {
        const columnName = typeof column6.name !== "string" ? column6.name.new : column6.name;
        const tableName = json22.tables[tableKey2].name;
        const columnType = json22.tables[tableKey2].columns[columnName].type;
        const columnDefault = json22.tables[tableKey2].columns[columnName].default;
        const columnGenerated = json22.tables[tableKey2].columns[columnName].generated;
        const columnOnUpdate = json22.tables[tableKey2].columns[columnName].onUpdate;
        const columnNotNull = json22.tables[tableKey2].columns[columnName].notNull;
        const columnAutoIncrement = json22.tables[tableKey2].columns[columnName].autoincrement;
        const columnPk = json22.tables[tableKey2].columns[columnName].primaryKey;
        const typeSchema = json22.tables[tableKey2].columns[columnName].typeSchema;
        const json1ColumnTypeSchema = json1.tables[tableKey2].columns[columnName].typeSchema;
        const compositePk = json22.tables[tableKey2].compositePrimaryKeys[`${tableName}_${columnName}`];
        if (typeof column6.name !== "string") {
          statements.push({
            type: "alter_table_rename_column",
            tableName,
            oldColumnName: column6.name.old,
            newColumnName: column6.name.new,
            schema: schema5
          });
        }
        if (column6.type?.type === "changed") {
          const arrayDefinitionRegex = /\[\d*(?:\[\d*\])*\]/g;
          const parsedNewColumnType = column6.type.new.replace(arrayDefinitionRegex, "");
          const parsedOldColumnType = column6.type.old.replace(arrayDefinitionRegex, "");
          const isNewTypeIsEnum = json22.enums[`${typeSchema}.${parsedNewColumnType}`];
          const isOldTypeIsEnum = json1.enums[`${json1ColumnTypeSchema}.${parsedOldColumnType}`];
          statements.push({
            type: "pg_alter_table_alter_column_set_type",
            tableName,
            columnName,
            typeSchema,
            newDataType: {
              name: column6.type.new,
              isEnum: isNewTypeIsEnum ? true : false
            },
            oldDataType: {
              name: column6.type.old,
              isEnum: isOldTypeIsEnum ? true : false
            },
            schema: schema5,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.primaryKey?.type === "deleted" || column6.primaryKey?.type === "changed" && !column6.primaryKey.new && typeof compositePk === "undefined") {
          dropPkStatements.push({
            ////
            type: "alter_table_alter_column_drop_pk",
            tableName,
            columnName,
            schema: schema5
          });
        }
        if (column6.default?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column6.default.value,
            schema: schema5,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.default?.type === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column6.default.new,
            oldDefaultValue: column6.default.old,
            schema: schema5,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.default?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_default",
            tableName,
            columnName,
            schema: schema5,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.notNull?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_notnull",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.notNull?.type === "changed") {
          const type = column6.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull";
          statements.push({
            type,
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.notNull?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_notnull",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.identity?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_identity",
            tableName,
            columnName,
            schema: schema5,
            identity: column6.identity.value
          });
        }
        if (column6.identity?.type === "changed") {
          statements.push({
            type: "alter_table_alter_column_change_identity",
            tableName,
            columnName,
            schema: schema5,
            identity: column6.identity.new,
            oldIdentity: column6.identity.old
          });
        }
        if (column6.identity?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_identity",
            tableName,
            columnName,
            schema: schema5
          });
        }
        if (column6.generated?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_generated",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (column6.generated?.type === "changed" && action !== "push") {
          statements.push({
            type: "alter_table_alter_column_alter_generated",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (column6.generated?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_generated",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (column6.primaryKey?.type === "added" || column6.primaryKey?.type === "changed" && column6.primaryKey.new) {
          const wasAutoincrement = statements.filter(
            (it) => it.type === "alter_table_alter_column_set_autoincrement"
          );
          if (wasAutoincrement.length === 0) {
            setPkStatements.push({
              type: "alter_table_alter_column_set_pk",
              tableName,
              schema: schema5,
              columnName
            });
          }
        }
        if (column6.onUpdate?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_on_update",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.onUpdate?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_on_update",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
      }
      return [...dropPkStatements, ...setPkStatements, ...statements];
    };
    prepareSqliteAlterColumns = (tableName, schema5, columns, json22) => {
      let statements = [];
      let dropPkStatements = [];
      let setPkStatements = [];
      for (const column6 of columns) {
        const columnName = typeof column6.name !== "string" ? column6.name.new : column6.name;
        const columnType = json22.tables[tableName].columns[columnName].type;
        const columnDefault = json22.tables[tableName].columns[columnName].default;
        const columnOnUpdate = json22.tables[tableName].columns[columnName].onUpdate;
        const columnNotNull = json22.tables[tableName].columns[columnName].notNull;
        const columnAutoIncrement = json22.tables[tableName].columns[columnName].autoincrement;
        const columnPk = json22.tables[tableName].columns[columnName].primaryKey;
        const columnGenerated = json22.tables[tableName].columns[columnName].generated;
        const compositePk = json22.tables[tableName].compositePrimaryKeys[`${tableName}_${columnName}`];
        if (column6.autoincrement?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_autoincrement",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.autoincrement?.type === "changed") {
          const type = column6.autoincrement.new ? "alter_table_alter_column_set_autoincrement" : "alter_table_alter_column_drop_autoincrement";
          statements.push({
            type,
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.autoincrement?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_autoincrement",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (typeof column6.name !== "string") {
          statements.push({
            type: "alter_table_rename_column",
            tableName,
            oldColumnName: column6.name.old,
            newColumnName: column6.name.new,
            schema: schema5
          });
        }
        if (column6.type?.type === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_type",
            tableName,
            columnName,
            newDataType: column6.type.new,
            oldDataType: column6.type.old,
            schema: schema5,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.primaryKey?.type === "deleted" || column6.primaryKey?.type === "changed" && !column6.primaryKey.new && typeof compositePk === "undefined") {
          dropPkStatements.push({
            ////
            type: "alter_table_alter_column_drop_pk",
            tableName,
            columnName,
            schema: schema5
          });
        }
        if (column6.default?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column6.default.value,
            schema: schema5,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.default?.type === "changed") {
          statements.push({
            type: "alter_table_alter_column_set_default",
            tableName,
            columnName,
            newDefaultValue: column6.default.new,
            oldDefaultValue: column6.default.old,
            schema: schema5,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.default?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_default",
            tableName,
            columnName,
            schema: schema5,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            newDataType: columnType,
            columnPk
          });
        }
        if (column6.notNull?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_notnull",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.notNull?.type === "changed") {
          const type = column6.notNull.new ? "alter_table_alter_column_set_notnull" : "alter_table_alter_column_drop_notnull";
          statements.push({
            type,
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.notNull?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_notnull",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.generated?.type === "added") {
          if (columnGenerated?.type === "virtual") {
            statements.push({
              type: "alter_table_alter_column_set_generated",
              tableName,
              columnName,
              schema: schema5,
              newDataType: columnType,
              columnDefault,
              columnOnUpdate,
              columnNotNull,
              columnAutoIncrement,
              columnPk,
              columnGenerated
            });
          } else {
            warning(
              `As SQLite docs mention: "It is not possible to ALTER TABLE ADD COLUMN a STORED column. One can add a VIRTUAL column, however", source: "https://www.sqlite.org/gencol.html"`
            );
          }
        }
        if (column6.generated?.type === "changed") {
          if (columnGenerated?.type === "virtual") {
            statements.push({
              type: "alter_table_alter_column_alter_generated",
              tableName,
              columnName,
              schema: schema5,
              newDataType: columnType,
              columnDefault,
              columnOnUpdate,
              columnNotNull,
              columnAutoIncrement,
              columnPk,
              columnGenerated
            });
          } else {
            warning(
              `As SQLite docs mention: "It is not possible to ALTER TABLE ADD COLUMN a STORED column. One can add a VIRTUAL column, however", source: "https://www.sqlite.org/gencol.html"`
            );
          }
        }
        if (column6.generated?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_generated",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk,
            columnGenerated
          });
        }
        if (column6.primaryKey?.type === "added" || column6.primaryKey?.type === "changed" && column6.primaryKey.new) {
          const wasAutoincrement = statements.filter(
            (it) => it.type === "alter_table_alter_column_set_autoincrement"
          );
          if (wasAutoincrement.length === 0) {
            setPkStatements.push({
              type: "alter_table_alter_column_set_pk",
              tableName,
              schema: schema5,
              columnName
            });
          }
        }
        if (column6.onUpdate?.type === "added") {
          statements.push({
            type: "alter_table_alter_column_set_on_update",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
        if (column6.onUpdate?.type === "deleted") {
          statements.push({
            type: "alter_table_alter_column_drop_on_update",
            tableName,
            columnName,
            schema: schema5,
            newDataType: columnType,
            columnDefault,
            columnOnUpdate,
            columnNotNull,
            columnAutoIncrement,
            columnPk
          });
        }
      }
      return [...dropPkStatements, ...setPkStatements, ...statements];
    };
    prepareRenamePolicyJsons = (tableName, schema5, renames) => {
      return renames.map((it) => {
        return {
          type: "rename_policy",
          tableName,
          oldName: it.from.name,
          newName: it.to.name,
          schema: schema5
        };
      });
    };
    prepareRenameIndPolicyJsons = (renames) => {
      return renames.map((it) => {
        return {
          type: "rename_ind_policy",
          tableKey: it.from.on,
          oldName: it.from.name,
          newName: it.to.name
        };
      });
    };
    prepareCreatePolicyJsons = (tableName, schema5, policies) => {
      return policies.map((it) => {
        return {
          type: "create_policy",
          tableName,
          data: it,
          schema: schema5
        };
      });
    };
    prepareCreateIndPolicyJsons = (policies) => {
      return policies.map((it) => {
        return {
          type: "create_ind_policy",
          tableName: it.on,
          data: it
        };
      });
    };
    prepareDropPolicyJsons = (tableName, schema5, policies) => {
      return policies.map((it) => {
        return {
          type: "drop_policy",
          tableName,
          data: it,
          schema: schema5
        };
      });
    };
    prepareDropIndPolicyJsons = (policies) => {
      return policies.map((it) => {
        return {
          type: "drop_ind_policy",
          tableName: it.on,
          data: it
        };
      });
    };
    prepareAlterPolicyJson = (tableName, schema5, oldPolicy, newPolicy) => {
      return {
        type: "alter_policy",
        tableName,
        oldData: oldPolicy,
        newData: newPolicy,
        schema: schema5
      };
    };
    prepareAlterIndPolicyJson = (oldPolicy, newPolicy) => {
      return {
        type: "alter_ind_policy",
        oldData: oldPolicy,
        newData: newPolicy
      };
    };
    preparePgCreateIndexesJson = (tableName, schema5, indexes, fullSchema, action) => {
      if (action === "push") {
        return Object.values(indexes).map((indexData) => {
          const unsquashedIndex = PgSquasher.unsquashIdxPush(indexData);
          const data = fullSchema.tables[`${schema5 === "" ? "public" : schema5}.${tableName}`].indexes[unsquashedIndex.name];
          return {
            type: "create_index_pg",
            tableName,
            data,
            schema: schema5
          };
        });
      }
      return Object.values(indexes).map((indexData) => {
        return {
          type: "create_index_pg",
          tableName,
          data: PgSquasher.unsquashIdx(indexData),
          schema: schema5
        };
      });
    };
    prepareCreateIndexesJson = (tableName, schema5, indexes, internal) => {
      return Object.values(indexes).map((indexData) => {
        return {
          type: "create_index",
          tableName,
          data: indexData,
          schema: schema5,
          internal
        };
      });
    };
    prepareCreateReferencesJson = (tableName, schema5, foreignKeys) => {
      return Object.values(foreignKeys).map((fkData) => {
        return {
          type: "create_reference",
          tableName,
          data: fkData,
          schema: schema5
        };
      });
    };
    prepareLibSQLCreateReferencesJson = (tableName, schema5, foreignKeys, json22, action) => {
      return Object.values(foreignKeys).map((fkData) => {
        const { columnsFrom, tableFrom, columnsTo } = action === "push" ? SQLiteSquasher.unsquashPushFK(fkData) : SQLiteSquasher.unsquashFK(fkData);
        let isMulticolumn = false;
        if (columnsFrom.length > 1 || columnsTo.length > 1) {
          isMulticolumn = true;
          return {
            type: "create_reference",
            tableName,
            data: fkData,
            schema: schema5,
            isMulticolumn
          };
        }
        const columnFrom = columnsFrom[0];
        const {
          notNull: columnNotNull,
          default: columnDefault,
          type: columnType
        } = json22.tables[tableFrom].columns[columnFrom];
        return {
          type: "create_reference",
          tableName,
          data: fkData,
          schema: schema5,
          columnNotNull,
          columnDefault,
          columnType
        };
      });
    };
    prepareDropReferencesJson = (tableName, schema5, foreignKeys) => {
      return Object.values(foreignKeys).map((fkData) => {
        return {
          type: "delete_reference",
          tableName,
          data: fkData,
          schema: schema5
        };
      });
    };
    prepareLibSQLDropReferencesJson = (tableName, schema5, foreignKeys, json22, meta, action) => {
      const statements = Object.values(foreignKeys).map((fkData) => {
        const { columnsFrom, tableFrom, columnsTo, name: name2, tableTo, onDelete, onUpdate } = action === "push" ? SQLiteSquasher.unsquashPushFK(fkData) : SQLiteSquasher.unsquashFK(fkData);
        const keys = Object.keys(json22.tables[tableName].columns);
        const filtered = columnsFrom.filter((it) => keys.includes(it));
        const fullDrop = filtered.length === 0;
        if (fullDrop) return;
        let isMulticolumn = false;
        if (columnsFrom.length > 1 || columnsTo.length > 1) {
          isMulticolumn = true;
          return {
            type: "delete_reference",
            tableName,
            data: fkData,
            schema: schema5,
            isMulticolumn
          };
        }
        const columnFrom = columnsFrom[0];
        const newTableName = getNewTableName(tableFrom, meta);
        const {
          notNull: columnNotNull,
          default: columnDefault,
          type: columnType
        } = json22.tables[newTableName].columns[columnFrom];
        const fkToSquash = {
          columnsFrom,
          columnsTo,
          name: name2,
          tableFrom: newTableName,
          tableTo,
          onDelete,
          onUpdate
        };
        const foreignKey = action === "push" ? SQLiteSquasher.squashPushFK(fkToSquash) : SQLiteSquasher.squashFK(fkToSquash);
        return {
          type: "delete_reference",
          tableName,
          data: foreignKey,
          schema: schema5,
          columnNotNull,
          columnDefault,
          columnType
        };
      });
      return statements.filter((it) => it);
    };
    prepareAlterReferencesJson = (tableName, schema5, foreignKeys) => {
      const stmts = [];
      Object.values(foreignKeys).map((val) => {
        stmts.push({
          type: "delete_reference",
          tableName,
          schema: schema5,
          data: val.__old
        });
        stmts.push({
          type: "create_reference",
          tableName,
          schema: schema5,
          data: val.__new
        });
      });
      return stmts;
    };
    prepareDropIndexesJson = (tableName, schema5, indexes) => {
      return Object.values(indexes).map((indexData) => {
        return {
          type: "drop_index",
          tableName,
          data: indexData,
          schema: schema5
        };
      });
    };
    prepareAddCompositePrimaryKeySqlite = (tableName, pks) => {
      return Object.values(pks).map((it) => {
        return {
          type: "create_composite_pk",
          tableName,
          data: it
        };
      });
    };
    prepareDeleteCompositePrimaryKeySqlite = (tableName, pks) => {
      return Object.values(pks).map((it) => {
        return {
          type: "delete_composite_pk",
          tableName,
          data: it
        };
      });
    };
    prepareAlterCompositePrimaryKeySqlite = (tableName, pks) => {
      return Object.values(pks).map((it) => {
        return {
          type: "alter_composite_pk",
          tableName,
          old: it.__old,
          new: it.__new
        };
      });
    };
    prepareAddCompositePrimaryKeyPg = (tableName, schema5, pks, json22) => {
      return Object.values(pks).map((it) => {
        const unsquashed = PgSquasher.unsquashPK(it);
        return {
          type: "create_composite_pk",
          tableName,
          data: it,
          schema: schema5,
          constraintName: PgSquasher.unsquashPK(it).name
        };
      });
    };
    prepareDeleteCompositePrimaryKeyPg = (tableName, schema5, pks, json1) => {
      return Object.values(pks).map((it) => {
        return {
          type: "delete_composite_pk",
          tableName,
          data: it,
          schema: schema5,
          constraintName: PgSquasher.unsquashPK(it).name
        };
      });
    };
    prepareAlterCompositePrimaryKeyPg = (tableName, schema5, pks, json1, json22) => {
      return Object.values(pks).map((it) => {
        return {
          type: "alter_composite_pk",
          tableName,
          old: it.__old,
          new: it.__new,
          schema: schema5,
          oldConstraintName: PgSquasher.unsquashPK(it.__old).name,
          newConstraintName: PgSquasher.unsquashPK(it.__new).name
        };
      });
    };
    prepareAddUniqueConstraintPg = (tableName, schema5, unqs) => {
      return Object.values(unqs).map((it) => {
        return {
          type: "create_unique_constraint",
          tableName,
          data: it,
          schema: schema5
        };
      });
    };
    prepareDeleteUniqueConstraintPg = (tableName, schema5, unqs) => {
      return Object.values(unqs).map((it) => {
        return {
          type: "delete_unique_constraint",
          tableName,
          data: it,
          schema: schema5
        };
      });
    };
    prepareAddCheckConstraint = (tableName, schema5, check) => {
      return Object.values(check).map((it) => {
        return {
          type: "create_check_constraint",
          tableName,
          data: it,
          schema: schema5
        };
      });
    };
    prepareDeleteCheckConstraint = (tableName, schema5, check) => {
      return Object.values(check).map((it) => {
        return {
          type: "delete_check_constraint",
          tableName,
          constraintName: PgSquasher.unsquashCheck(it).name,
          schema: schema5
        };
      });
    };
    prepareAddCompositePrimaryKeyMySql = (tableName, pks, json1, json22) => {
      const res = [];
      for (const it of Object.values(pks)) {
        const unsquashed = MySqlSquasher.unsquashPK(it);
        if (unsquashed.columns.length === 1 && json1.tables[tableName]?.columns[unsquashed.columns[0]]?.primaryKey) {
          continue;
        }
        res.push({
          type: "create_composite_pk",
          tableName,
          data: it,
          constraintName: unsquashed.name
        });
      }
      return res;
    };
    prepareDeleteCompositePrimaryKeyMySql = (tableName, pks, json1) => {
      return Object.values(pks).map((it) => {
        const unsquashed = MySqlSquasher.unsquashPK(it);
        return {
          type: "delete_composite_pk",
          tableName,
          data: it
        };
      });
    };
    prepareAlterCompositePrimaryKeyMySql = (tableName, pks, json1, json22) => {
      return Object.values(pks).map((it) => {
        return {
          type: "alter_composite_pk",
          tableName,
          old: it.__old,
          new: it.__new,
          oldConstraintName: json1.tables[tableName].compositePrimaryKeys[MySqlSquasher.unsquashPK(it.__old).name].name,
          newConstraintName: json22.tables[tableName].compositePrimaryKeys[MySqlSquasher.unsquashPK(it.__new).name].name
        };
      });
    };
    preparePgCreateViewJson = (name2, schema5, definition, materialized, withNoData = false, withOption, using, tablespace) => {
      return {
        type: "create_view",
        name: name2,
        schema: schema5,
        definition,
        with: withOption,
        materialized,
        withNoData,
        using,
        tablespace
      };
    };
    prepareMySqlCreateViewJson = (name2, definition, meta, replace = false) => {
      const { algorithm, sqlSecurity, withCheckOption } = MySqlSquasher.unsquashView(meta);
      return {
        type: "mysql_create_view",
        name: name2,
        definition,
        algorithm,
        sqlSecurity,
        withCheckOption,
        replace
      };
    };
    prepareSqliteCreateViewJson = (name2, definition) => {
      return {
        type: "sqlite_create_view",
        name: name2,
        definition
      };
    };
    prepareDropViewJson = (name2, schema5, materialized) => {
      const resObject = { name: name2, type: "drop_view" };
      if (schema5) resObject["schema"] = schema5;
      if (materialized) resObject["materialized"] = materialized;
      return resObject;
    };
    prepareRenameViewJson = (to, from, schema5, materialized) => {
      const resObject = {
        type: "rename_view",
        nameTo: to,
        nameFrom: from
      };
      if (schema5) resObject["schema"] = schema5;
      if (materialized) resObject["materialized"] = materialized;
      return resObject;
    };
    preparePgAlterViewAlterSchemaJson = (to, from, name2, materialized) => {
      const returnObject = {
        type: "alter_view_alter_schema",
        fromSchema: from,
        toSchema: to,
        name: name2
      };
      if (materialized) returnObject["materialized"] = materialized;
      return returnObject;
    };
    preparePgAlterViewAddWithOptionJson = (name2, schema5, materialized, withOption) => {
      return {
        type: "alter_view_add_with_option",
        name: name2,
        schema: schema5,
        materialized,
        with: withOption
      };
    };
    preparePgAlterViewDropWithOptionJson = (name2, schema5, materialized, withOption) => {
      return {
        type: "alter_view_drop_with_option",
        name: name2,
        schema: schema5,
        materialized,
        with: withOption
      };
    };
    preparePgAlterViewAlterTablespaceJson = (name2, schema5, materialized, to) => {
      return {
        type: "alter_view_alter_tablespace",
        name: name2,
        schema: schema5,
        materialized,
        toTablespace: to
      };
    };
    preparePgAlterViewAlterUsingJson = (name2, schema5, materialized, to) => {
      return {
        type: "alter_view_alter_using",
        name: name2,
        schema: schema5,
        materialized,
        toUsing: to
      };
    };
    prepareMySqlAlterView = (view5) => {
      return { type: "alter_mysql_view", ...view5 };
    };
  }
});

// src/statementCombiner.ts
var prepareLibSQLRecreateTable, prepareSQLiteRecreateTable, libSQLCombineStatements, sqliteCombineStatements, prepareSingleStoreRecreateTable, singleStoreCombineStatements;
var init_statementCombiner = __esm({
  "src/statementCombiner.ts"() {
    "use strict";
    init_jsonStatements();
    init_sqliteSchema();
    prepareLibSQLRecreateTable = (table6, action) => {
      const { name: name2, columns, uniqueConstraints, indexes, checkConstraints } = table6;
      const composites = Object.values(table6.compositePrimaryKeys).map(
        (it) => SQLiteSquasher.unsquashPK(it)
      );
      const references2 = Object.values(table6.foreignKeys);
      const fks = references2.map(
        (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it)
      );
      const statements = [
        {
          type: "recreate_table",
          tableName: name2,
          columns: Object.values(columns),
          compositePKs: composites,
          referenceData: fks,
          uniqueConstraints: Object.values(uniqueConstraints),
          checkConstraints: Object.values(checkConstraints)
        }
      ];
      if (Object.keys(indexes).length) {
        statements.push(...prepareCreateIndexesJson(name2, "", indexes));
      }
      return statements;
    };
    prepareSQLiteRecreateTable = (table6, action) => {
      const { name: name2, columns, uniqueConstraints, indexes, checkConstraints } = table6;
      const composites = Object.values(table6.compositePrimaryKeys).map(
        (it) => SQLiteSquasher.unsquashPK(it)
      );
      const references2 = Object.values(table6.foreignKeys);
      const fks = references2.map(
        (it) => action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it)
      );
      const statements = [
        {
          type: "recreate_table",
          tableName: name2,
          columns: Object.values(columns),
          compositePKs: composites,
          referenceData: fks,
          uniqueConstraints: Object.values(uniqueConstraints),
          checkConstraints: Object.values(checkConstraints)
        }
      ];
      if (Object.keys(indexes).length) {
        statements.push(...prepareCreateIndexesJson(name2, "", indexes));
      }
      return statements;
    };
    libSQLCombineStatements = (statements, json22, action) => {
      const newStatements = {};
      for (const statement of statements) {
        if (statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareLibSQLRecreateTable(json22.tables[tableName2], action);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareLibSQLRecreateTable(json22.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default") {
          const { tableName: tableName2, columnName, columnPk } = statement;
          const columnIsPartOfForeignKey = Object.values(
            json22.tables[tableName2].foreignKeys
          ).some((it) => {
            const unsquashFk = action === "push" ? SQLiteSquasher.unsquashPushFK(it) : SQLiteSquasher.unsquashFK(it);
            return unsquashFk.columnsFrom.includes(columnName);
          });
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2 && (columnIsPartOfForeignKey || columnPk)) {
            newStatements[tableName2] = prepareLibSQLRecreateTable(json22.tables[tableName2], action);
            continue;
          }
          if (statementsForTable2 && (columnIsPartOfForeignKey || columnPk)) {
            if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
              const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
              const preparedStatements = prepareLibSQLRecreateTable(json22.tables[tableName2], action);
              if (wasRename) {
                newStatements[tableName2].push(...preparedStatements);
              } else {
                newStatements[tableName2] = preparedStatements;
              }
            }
            continue;
          }
          if (statementsForTable2 && !(columnIsPartOfForeignKey || columnPk)) {
            if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
              newStatements[tableName2].push(statement);
            }
            continue;
          }
          newStatements[tableName2] = [statement];
          continue;
        }
        if (statement.type === "create_reference") {
          const tableName2 = statement.tableName;
          const data = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = statement.isMulticolumn ? prepareLibSQLRecreateTable(json22.tables[tableName2], action) : [statement];
            continue;
          }
          if (!statement.isMulticolumn && statementsForTable2.some(
            (st) => st.type === "sqlite_alter_table_add_column" && st.column.name === data.columnsFrom[0]
          )) {
            continue;
          }
          if (statement.isMulticolumn) {
            if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
              const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
              const preparedStatements = prepareLibSQLRecreateTable(json22.tables[tableName2], action);
              if (wasRename) {
                newStatements[tableName2].push(...preparedStatements);
              } else {
                newStatements[tableName2] = preparedStatements;
              }
              continue;
            }
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            newStatements[tableName2].push(statement);
          }
          continue;
        }
        if (statement.type === "delete_reference") {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareLibSQLRecreateTable(json22.tables[tableName2], action);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareLibSQLRecreateTable(json22.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if (statement.type === "sqlite_alter_table_add_column" && statement.column.primaryKey) {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareLibSQLRecreateTable(json22.tables[tableName2], action);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareLibSQLRecreateTable(json22.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName;
        const statementsForTable = newStatements[tableName];
        if (!statementsForTable) {
          newStatements[tableName] = [statement];
          continue;
        }
        if (!statementsForTable.some(({ type }) => type === "recreate_table")) {
          newStatements[tableName].push(statement);
        }
      }
      const combinedStatements = Object.values(newStatements).flat();
      const renamedTables = combinedStatements.filter((it) => it.type === "rename_table");
      const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column");
      const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column");
      return [...renamedTables, ...renamedColumns, ...rest];
    };
    sqliteCombineStatements = (statements, json22, action) => {
      const newStatements = {};
      for (const statement of statements) {
        if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_default" || statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "delete_reference" || statement.type === "alter_reference" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk" || statement.type === "create_unique_constraint" || statement.type === "delete_unique_constraint" || statement.type === "create_check_constraint" || statement.type === "delete_check_constraint") {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSQLiteRecreateTable(json22.tables[tableName2], action);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareSQLiteRecreateTable(json22.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if (statement.type === "sqlite_alter_table_add_column" && statement.column.primaryKey) {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSQLiteRecreateTable(json22.tables[tableName2], action);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareSQLiteRecreateTable(json22.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if (statement.type === "create_reference") {
          const tableName2 = statement.tableName;
          const data = action === "push" ? SQLiteSquasher.unsquashPushFK(statement.data) : SQLiteSquasher.unsquashFK(statement.data);
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSQLiteRecreateTable(json22.tables[tableName2], action);
            continue;
          }
          if (data.columnsFrom.length === 1 && statementsForTable2.some(
            (st) => st.type === "sqlite_alter_table_add_column" && st.column.name === data.columnsFrom[0]
          )) {
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareSQLiteRecreateTable(json22.tables[tableName2], action);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName;
        const statementsForTable = newStatements[tableName];
        if (!statementsForTable) {
          newStatements[tableName] = [statement];
          continue;
        }
        if (!statementsForTable.some(({ type }) => type === "recreate_table")) {
          newStatements[tableName].push(statement);
        }
      }
      const combinedStatements = Object.values(newStatements).flat();
      const renamedTables = combinedStatements.filter((it) => it.type === "rename_table");
      const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column");
      const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column");
      return [...renamedTables, ...renamedColumns, ...rest];
    };
    prepareSingleStoreRecreateTable = (table6) => {
      const { name: name2, columns, uniqueConstraints, indexes, compositePrimaryKeys } = table6;
      const composites = Object.values(compositePrimaryKeys);
      const statements = [
        {
          type: "singlestore_recreate_table",
          tableName: name2,
          columns: Object.values(columns),
          compositePKs: composites,
          uniqueConstraints: Object.values(uniqueConstraints)
        }
      ];
      if (Object.keys(indexes).length) {
        statements.push(...prepareCreateIndexesJson(name2, "", indexes));
      }
      return statements;
    };
    singleStoreCombineStatements = (statements, json22) => {
      const newStatements = {};
      for (const statement of statements) {
        if (statement.type === "alter_table_alter_column_set_type" || statement.type === "alter_table_alter_column_set_notnull" || statement.type === "alter_table_alter_column_drop_notnull" || statement.type === "alter_table_alter_column_drop_autoincrement" || statement.type === "alter_table_alter_column_set_autoincrement" || statement.type === "alter_table_alter_column_drop_pk" || statement.type === "alter_table_alter_column_set_pk" || statement.type === "create_composite_pk" || statement.type === "alter_composite_pk" || statement.type === "delete_composite_pk") {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSingleStoreRecreateTable(json22.tables[tableName2]);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(
              ({ type }) => type === "rename_table" || type === "alter_table_rename_column"
            );
            const preparedStatements = prepareSingleStoreRecreateTable(json22.tables[tableName2]);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if ((statement.type === "alter_table_alter_column_drop_default" || statement.type === "alter_table_alter_column_set_default") && statement.columnNotNull) {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSingleStoreRecreateTable(json22.tables[tableName2]);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareSingleStoreRecreateTable(json22.tables[tableName2]);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        if (statement.type === "alter_table_add_column" && statement.column.primaryKey) {
          const tableName2 = statement.tableName;
          const statementsForTable2 = newStatements[tableName2];
          if (!statementsForTable2) {
            newStatements[tableName2] = prepareSingleStoreRecreateTable(json22.tables[tableName2]);
            continue;
          }
          if (!statementsForTable2.some(({ type }) => type === "recreate_table")) {
            const wasRename = statementsForTable2.some(({ type }) => type === "rename_table");
            const preparedStatements = prepareSingleStoreRecreateTable(json22.tables[tableName2]);
            if (wasRename) {
              newStatements[tableName2].push(...preparedStatements);
            } else {
              newStatements[tableName2] = preparedStatements;
            }
            continue;
          }
          continue;
        }
        const tableName = statement.type === "rename_table" ? statement.tableNameTo : statement.tableName;
        const statementsForTable = newStatements[tableName];
        if (!statementsForTable) {
          newStatements[tableName] = [statement];
          continue;
        }
        if (!statementsForTable.some(({ type }) => type === "singlestore_recreate_table")) {
          newStatements[tableName].push(statement);
        }
      }
      const combinedStatements = Object.values(newStatements).flat();
      const renamedTables = combinedStatements.filter((it) => it.type === "rename_table");
      const renamedColumns = combinedStatements.filter((it) => it.type === "alter_table_rename_column");
      const rest = combinedStatements.filter((it) => it.type !== "rename_table" && it.type !== "alter_table_rename_column");
      return [...renamedTables, ...renamedColumns, ...rest];
    };
  }
});

// src/snapshotsDiffer.ts
var snapshotsDiffer_exports = {};
__export(snapshotsDiffer_exports, {
  alteredPgViewSchema: () => alteredPgViewSchema,
  alteredTableScheme: () => alteredTableScheme,
  applyLibSQLSnapshotsDiff: () => applyLibSQLSnapshotsDiff,
  applyMysqlSnapshotsDiff: () => applyMysqlSnapshotsDiff,
  applyPgSnapshotsDiff: () => applyPgSnapshotsDiff,
  applySingleStoreSnapshotsDiff: () => applySingleStoreSnapshotsDiff,
  applySqliteSnapshotsDiff: () => applySqliteSnapshotsDiff,
  diffResultScheme: () => diffResultScheme,
  diffResultSchemeMysql: () => diffResultSchemeMysql,
  diffResultSchemeSQLite: () => diffResultSchemeSQLite,
  diffResultSchemeSingleStore: () => diffResultSchemeSingleStore,
  makePatched: () => makePatched,
  makeSelfOrPatched: () => makeSelfOrPatched
});
var makeChanged, makeSelfOrChanged, makePatched, makeSelfOrPatched, columnSchema, alteredColumnSchema, enumSchema3, changedEnumSchema, tableScheme, alteredTableScheme, alteredViewCommon, alteredPgViewSchema, alteredMySqlViewSchema, diffResultScheme, diffResultSchemeMysql, diffResultSchemeSingleStore, diffResultSchemeSQLite, schemaChangeFor, nameChangeFor, nameSchemaChangeFor, columnChangeFor, applyPgSnapshotsDiff, applyMysqlSnapshotsDiff, applySingleStoreSnapshotsDiff, applySqliteSnapshotsDiff, applyLibSQLSnapshotsDiff;
var init_snapshotsDiffer = __esm({
  "src/snapshotsDiffer.ts"() {
    "use strict";
    init_esm();
    init_jsonDiffer();
    init_sqlgenerator();
    init_jsonStatements();
    init_global();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    init_statementCombiner();
    init_utils();
    makeChanged = (schema5) => {
      return objectType({
        type: enumType(["changed"]),
        old: schema5,
        new: schema5
      });
    };
    makeSelfOrChanged = (schema5) => {
      return unionType([
        schema5,
        objectType({
          type: enumType(["changed"]),
          old: schema5,
          new: schema5
        })
      ]);
    };
    makePatched = (schema5) => {
      return unionType([
        objectType({
          type: literalType("added"),
          value: schema5
        }),
        objectType({
          type: literalType("deleted"),
          value: schema5
        }),
        objectType({
          type: literalType("changed"),
          old: schema5,
          new: schema5
        })
      ]);
    };
    makeSelfOrPatched = (schema5) => {
      return unionType([
        objectType({
          type: literalType("none"),
          value: schema5
        }),
        objectType({
          type: literalType("added"),
          value: schema5
        }),
        objectType({
          type: literalType("deleted"),
          value: schema5
        }),
        objectType({
          type: literalType("changed"),
          old: schema5,
          new: schema5
        })
      ]);
    };
    columnSchema = objectType({
      name: stringType(),
      type: stringType(),
      typeSchema: stringType().optional(),
      primaryKey: booleanType().optional(),
      default: anyType().optional(),
      notNull: booleanType().optional(),
      // should it be optional? should if be here?
      autoincrement: booleanType().optional(),
      onUpdate: booleanType().optional(),
      isUnique: anyType().optional(),
      uniqueName: stringType().optional(),
      nullsNotDistinct: booleanType().optional(),
      generated: objectType({
        as: stringType(),
        type: enumType(["stored", "virtual"]).default("stored")
      }).optional(),
      identity: stringType().optional()
    }).strict();
    alteredColumnSchema = objectType({
      name: makeSelfOrChanged(stringType()),
      type: makeChanged(stringType()).optional(),
      default: makePatched(anyType()).optional(),
      primaryKey: makePatched(booleanType()).optional(),
      notNull: makePatched(booleanType()).optional(),
      typeSchema: makePatched(stringType()).optional(),
      onUpdate: makePatched(booleanType()).optional(),
      autoincrement: makePatched(booleanType()).optional(),
      generated: makePatched(
        objectType({
          as: stringType(),
          type: enumType(["stored", "virtual"]).default("stored")
        })
      ).optional(),
      identity: makePatched(stringType()).optional()
    }).strict();
    enumSchema3 = objectType({
      name: stringType(),
      schema: stringType(),
      values: arrayType(stringType())
    }).strict();
    changedEnumSchema = objectType({
      name: stringType(),
      schema: stringType(),
      addedValues: objectType({
        before: stringType(),
        value: stringType()
      }).array(),
      deletedValues: arrayType(stringType())
    }).strict();
    tableScheme = objectType({
      name: stringType(),
      schema: stringType().default(""),
      columns: recordType(stringType(), columnSchema),
      indexes: recordType(stringType(), stringType()),
      foreignKeys: recordType(stringType(), stringType()),
      compositePrimaryKeys: recordType(stringType(), stringType()).default({}),
      uniqueConstraints: recordType(stringType(), stringType()).default({}),
      policies: recordType(stringType(), stringType()).default({}),
      checkConstraints: recordType(stringType(), stringType()).default({}),
      isRLSEnabled: booleanType().default(false)
    }).strict();
    alteredTableScheme = objectType({
      name: stringType(),
      schema: stringType(),
      altered: alteredColumnSchema.array(),
      addedIndexes: recordType(stringType(), stringType()),
      deletedIndexes: recordType(stringType(), stringType()),
      alteredIndexes: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        }).strict()
      ),
      addedForeignKeys: recordType(stringType(), stringType()),
      deletedForeignKeys: recordType(stringType(), stringType()),
      alteredForeignKeys: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        }).strict()
      ),
      addedCompositePKs: recordType(stringType(), stringType()),
      deletedCompositePKs: recordType(stringType(), stringType()),
      alteredCompositePKs: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        })
      ),
      addedUniqueConstraints: recordType(stringType(), stringType()),
      deletedUniqueConstraints: recordType(stringType(), stringType()),
      alteredUniqueConstraints: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        })
      ),
      addedPolicies: recordType(stringType(), stringType()),
      deletedPolicies: recordType(stringType(), stringType()),
      alteredPolicies: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        })
      ),
      addedCheckConstraints: recordType(
        stringType(),
        stringType()
      ),
      deletedCheckConstraints: recordType(
        stringType(),
        stringType()
      ),
      alteredCheckConstraints: recordType(
        stringType(),
        objectType({
          __new: stringType(),
          __old: stringType()
        })
      )
    }).strict();
    alteredViewCommon = objectType({
      name: stringType(),
      alteredDefinition: objectType({
        __old: stringType(),
        __new: stringType()
      }).strict().optional(),
      alteredExisting: objectType({
        __old: booleanType(),
        __new: booleanType()
      }).strict().optional()
    });
    alteredPgViewSchema = alteredViewCommon.merge(
      objectType({
        schema: stringType(),
        deletedWithOption: mergedViewWithOption2.optional(),
        addedWithOption: mergedViewWithOption2.optional(),
        addedWith: mergedViewWithOption2.optional(),
        deletedWith: mergedViewWithOption2.optional(),
        alteredWith: mergedViewWithOption2.optional(),
        alteredSchema: objectType({
          __old: stringType(),
          __new: stringType()
        }).strict().optional(),
        alteredTablespace: objectType({
          __old: stringType(),
          __new: stringType()
        }).strict().optional(),
        alteredUsing: objectType({
          __old: stringType(),
          __new: stringType()
        }).strict().optional()
      }).strict()
    );
    alteredMySqlViewSchema = alteredViewCommon.merge(
      objectType({
        alteredMeta: objectType({
          __old: stringType(),
          __new: stringType()
        }).strict().optional()
      }).strict()
    );
    diffResultScheme = objectType({
      alteredTablesWithColumns: alteredTableScheme.array(),
      alteredEnums: changedEnumSchema.array(),
      alteredSequences: sequenceSquashed2.array(),
      alteredRoles: roleSchema2.array(),
      alteredPolicies: policySquashed2.array(),
      alteredViews: alteredPgViewSchema.array()
    }).strict();
    diffResultSchemeMysql = objectType({
      alteredTablesWithColumns: alteredTableScheme.array(),
      alteredEnums: neverType().array(),
      alteredViews: alteredMySqlViewSchema.array()
    });
    diffResultSchemeSingleStore = objectType({
      alteredTablesWithColumns: alteredTableScheme.array(),
      alteredEnums: neverType().array()
    });
    diffResultSchemeSQLite = objectType({
      alteredTablesWithColumns: alteredTableScheme.array(),
      alteredEnums: neverType().array(),
      alteredViews: alteredViewCommon.array()
    });
    schemaChangeFor = (table6, renamedSchemas) => {
      for (let ren of renamedSchemas) {
        if (table6.schema === ren.from.name) {
          return { key: `${ren.to.name}.${table6.name}`, schema: ren.to.name };
        }
      }
      return {
        key: `${table6.schema || "public"}.${table6.name}`,
        schema: table6.schema
      };
    };
    nameChangeFor = (table6, renamed) => {
      for (let ren of renamed) {
        if (table6.name === ren.from.name) {
          return { name: ren.to.name };
        }
      }
      return {
        name: table6.name
      };
    };
    nameSchemaChangeFor = (table6, renamedTables) => {
      for (let ren of renamedTables) {
        if (table6.name === ren.from.name && table6.schema === ren.from.schema) {
          return {
            key: `${ren.to.schema || "public"}.${ren.to.name}`,
            name: ren.to.name,
            schema: ren.to.schema
          };
        }
      }
      return {
        key: `${table6.schema || "public"}.${table6.name}`,
        name: table6.name,
        schema: table6.schema
      };
    };
    columnChangeFor = (column6, renamedColumns) => {
      for (let ren of renamedColumns) {
        if (column6 === ren.from.name) {
          return ren.to.name;
        }
      }
      return column6;
    };
    applyPgSnapshotsDiff = async (json1, json22, schemasResolver2, enumsResolver2, sequencesResolver2, policyResolver2, indPolicyResolver2, roleResolver2, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
      const schemasDiff = diffSchemasOrTables(json1.schemas, json22.schemas);
      const {
        created: createdSchemas,
        deleted: deletedSchemas,
        renamed: renamedSchemas
      } = await schemasResolver2({
        created: schemasDiff.added.map((it) => ({ name: it })),
        deleted: schemasDiff.deleted.map((it) => ({ name: it }))
      });
      const schemasPatchedSnap1 = copy(json1);
      schemasPatchedSnap1.tables = mapEntries(
        schemasPatchedSnap1.tables,
        (_2, it) => {
          const { key, schema: schema5 } = schemaChangeFor(it, renamedSchemas);
          it.schema = schema5;
          return [key, it];
        }
      );
      schemasPatchedSnap1.enums = mapEntries(schemasPatchedSnap1.enums, (_2, it) => {
        const { key, schema: schema5 } = schemaChangeFor(it, renamedSchemas);
        it.schema = schema5;
        return [key, it];
      });
      const enumsDiff = diffSchemasOrTables(schemasPatchedSnap1.enums, json22.enums);
      const {
        created: createdEnums,
        deleted: deletedEnums,
        renamed: renamedEnums,
        moved: movedEnums
      } = await enumsResolver2({
        created: enumsDiff.added,
        deleted: enumsDiff.deleted
      });
      schemasPatchedSnap1.enums = mapEntries(schemasPatchedSnap1.enums, (_2, it) => {
        const { key, name: name2, schema: schema5 } = nameSchemaChangeFor(it, renamedEnums);
        it.name = name2;
        it.schema = schema5;
        return [key, it];
      });
      const columnTypesChangeMap = renamedEnums.reduce(
        (acc, it) => {
          acc[`${it.from.schema}.${it.from.name}`] = {
            nameFrom: it.from.name,
            nameTo: it.to.name,
            schemaFrom: it.from.schema,
            schemaTo: it.to.schema
          };
          return acc;
        },
        {}
      );
      const columnTypesMovesMap = movedEnums.reduce(
        (acc, it) => {
          acc[`${it.schemaFrom}.${it.name}`] = {
            nameFrom: it.name,
            nameTo: it.name,
            schemaFrom: it.schemaFrom,
            schemaTo: it.schemaTo
          };
          return acc;
        },
        {}
      );
      schemasPatchedSnap1.tables = mapEntries(
        schemasPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapValues(tableValue.columns, (column6) => {
            const key = `${column6.typeSchema || "public"}.${column6.type}`;
            const change = columnTypesChangeMap[key] || columnTypesMovesMap[key];
            if (change) {
              column6.type = change.nameTo;
              column6.typeSchema = change.schemaTo;
            }
            return column6;
          });
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      schemasPatchedSnap1.sequences = mapEntries(
        schemasPatchedSnap1.sequences,
        (_2, it) => {
          const { key, schema: schema5 } = schemaChangeFor(it, renamedSchemas);
          it.schema = schema5;
          return [key, it];
        }
      );
      const sequencesDiff = diffSchemasOrTables(
        schemasPatchedSnap1.sequences,
        json22.sequences
      );
      const {
        created: createdSequences,
        deleted: deletedSequences,
        renamed: renamedSequences,
        moved: movedSequences
      } = await sequencesResolver2({
        created: sequencesDiff.added,
        deleted: sequencesDiff.deleted
      });
      schemasPatchedSnap1.sequences = mapEntries(
        schemasPatchedSnap1.sequences,
        (_2, it) => {
          const { key, name: name2, schema: schema5 } = nameSchemaChangeFor(it, renamedSequences);
          it.name = name2;
          it.schema = schema5;
          return [key, it];
        }
      );
      const sequencesChangeMap = renamedSequences.reduce(
        (acc, it) => {
          acc[`${it.from.schema}.${it.from.name}`] = {
            nameFrom: it.from.name,
            nameTo: it.to.name,
            schemaFrom: it.from.schema,
            schemaTo: it.to.schema
          };
          return acc;
        },
        {}
      );
      const sequencesMovesMap = movedSequences.reduce(
        (acc, it) => {
          acc[`${it.schemaFrom}.${it.name}`] = {
            nameFrom: it.name,
            nameTo: it.name,
            schemaFrom: it.schemaFrom,
            schemaTo: it.schemaTo
          };
          return acc;
        },
        {}
      );
      schemasPatchedSnap1.tables = mapEntries(
        schemasPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapValues(tableValue.columns, (column6) => {
            const key = `${column6.typeSchema || "public"}.${column6.type}`;
            const change = sequencesChangeMap[key] || sequencesMovesMap[key];
            if (change) {
              column6.type = change.nameTo;
              column6.typeSchema = change.schemaTo;
            }
            return column6;
          });
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const rolesDiff = diffSchemasOrTables(
        schemasPatchedSnap1.roles,
        json22.roles
      );
      const {
        created: createdRoles,
        deleted: deletedRoles,
        renamed: renamedRoles
      } = await roleResolver2({
        created: rolesDiff.added,
        deleted: rolesDiff.deleted
      });
      schemasPatchedSnap1.roles = mapEntries(
        schemasPatchedSnap1.roles,
        (_2, it) => {
          const { name: name2 } = nameChangeFor(it, renamedRoles);
          it.name = name2;
          return [name2, it];
        }
      );
      const rolesChangeMap = renamedRoles.reduce(
        (acc, it) => {
          acc[it.from.name] = {
            nameFrom: it.from.name,
            nameTo: it.to.name
          };
          return acc;
        },
        {}
      );
      schemasPatchedSnap1.roles = mapEntries(
        schemasPatchedSnap1.roles,
        (roleKey, roleValue) => {
          const key = roleKey;
          const change = rolesChangeMap[key];
          if (change) {
            roleValue.name = change.nameTo;
          }
          return [roleKey, roleValue];
        }
      );
      const tablesDiff = diffSchemasOrTables(
        schemasPatchedSnap1.tables,
        json22.tables
      );
      const {
        created: createdTables,
        deleted: deletedTables,
        moved: movedTables,
        renamed: renamedTables
        // renamed or moved
      } = await tablesResolver2({
        created: tablesDiff.added,
        deleted: tablesDiff.deleted
      });
      const tablesPatchedSnap1 = copy(schemasPatchedSnap1);
      tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_2, it) => {
        const { key, name: name2, schema: schema5 } = nameSchemaChangeFor(it, renamedTables);
        it.name = name2;
        it.schema = schema5;
        return [key, it];
      });
      const res = diffColumns(tablesPatchedSnap1.tables, json22.tables);
      const columnRenames = [];
      const columnCreates = [];
      const columnDeletes = [];
      for (let entry of Object.values(res)) {
        const { renamed, created: created2, deleted: deleted2 } = await columnsResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.columns.deleted,
          created: entry.columns.added
        });
        if (created2.length > 0) {
          columnCreates.push({
            table: entry.name,
            schema: entry.schema,
            columns: created2
          });
        }
        if (deleted2.length > 0) {
          columnDeletes.push({
            table: entry.name,
            schema: entry.schema,
            columns: deleted2
          });
        }
        if (renamed.length > 0) {
          columnRenames.push({
            table: entry.name,
            schema: entry.schema,
            renames: renamed
          });
        }
      }
      const columnRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[`${it.schema || "public"}.${it.table}`] = it.renames;
          return acc;
        },
        {}
      );
      const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
      columnsPatchedSnap1.tables = mapEntries(
        columnsPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapKeys(
            tableValue.columns,
            (columnKey, column6) => {
              const rens = columnRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || [];
              const newName = columnChangeFor(columnKey, rens);
              column6.name = newName;
              return newName;
            }
          );
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const policyRes = diffPolicies(tablesPatchedSnap1.tables, json22.tables);
      const policyRenames = [];
      const policyCreates = [];
      const policyDeletes = [];
      for (let entry of Object.values(policyRes)) {
        const { renamed, created: created2, deleted: deleted2 } = await policyResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.policies.deleted.map(
            action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy
          ),
          created: entry.policies.added.map(action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy)
        });
        if (created2.length > 0) {
          policyCreates.push({
            table: entry.name,
            schema: entry.schema,
            columns: created2
          });
        }
        if (deleted2.length > 0) {
          policyDeletes.push({
            table: entry.name,
            schema: entry.schema,
            columns: deleted2
          });
        }
        if (renamed.length > 0) {
          policyRenames.push({
            table: entry.name,
            schema: entry.schema,
            renames: renamed
          });
        }
      }
      const policyRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[`${it.schema || "public"}.${it.table}`] = it.renames;
          return acc;
        },
        {}
      );
      const policyPatchedSnap1 = copy(tablesPatchedSnap1);
      policyPatchedSnap1.tables = mapEntries(
        policyPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedPolicies = mapKeys(
            tableValue.policies,
            (policyKey, policy5) => {
              const rens = policyRenamesDict[`${tableValue.schema || "public"}.${tableValue.name}`] || [];
              const newName = columnChangeFor(policyKey, rens);
              const unsquashedPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(policy5) : PgSquasher.unsquashPolicy(policy5);
              unsquashedPolicy.name = newName;
              policy5 = PgSquasher.squashPolicy(unsquashedPolicy);
              return newName;
            }
          );
          tableValue.policies = patchedPolicies;
          return [tableKey2, tableValue];
        }
      );
      const indPolicyRes = diffIndPolicies(policyPatchedSnap1.policies, json22.policies);
      const indPolicyCreates = [];
      const indPolicyDeletes = [];
      const { renamed: indPolicyRenames, created, deleted } = await indPolicyResolver2({
        deleted: indPolicyRes.deleted.map(
          (t) => action === "push" ? PgSquasher.unsquashPolicyPush(t.values) : PgSquasher.unsquashPolicy(t.values)
        ),
        created: indPolicyRes.added.map(
          (t) => action === "push" ? PgSquasher.unsquashPolicyPush(t.values) : PgSquasher.unsquashPolicy(t.values)
        )
      });
      if (created.length > 0) {
        indPolicyCreates.push({
          policies: created
        });
      }
      if (deleted.length > 0) {
        indPolicyDeletes.push({
          policies: deleted
        });
      }
      const indPolicyRenamesDict = indPolicyRenames.reduce(
        (acc, it) => {
          acc[it.from.name] = {
            nameFrom: it.from.name,
            nameTo: it.to.name
          };
          return acc;
        },
        {}
      );
      const indPolicyPatchedSnap1 = copy(policyPatchedSnap1);
      indPolicyPatchedSnap1.policies = mapEntries(
        indPolicyPatchedSnap1.policies,
        (policyKey, policyValue) => {
          const key = policyKey;
          const change = indPolicyRenamesDict[key];
          if (change) {
            policyValue.name = change.nameTo;
          }
          return [policyKey, policyValue];
        }
      );
      const viewsDiff = diffSchemasOrTables(indPolicyPatchedSnap1.views, json22.views);
      const {
        created: createdViews,
        deleted: deletedViews,
        renamed: renamedViews,
        moved: movedViews
      } = await viewsResolver2({
        created: viewsDiff.added,
        deleted: viewsDiff.deleted
      });
      const renamesViewDic = {};
      renamedViews.forEach((it) => {
        renamesViewDic[`${it.from.schema}.${it.from.name}`] = { to: it.to.name, from: it.from.name };
      });
      const movedViewDic = {};
      movedViews.forEach((it) => {
        movedViewDic[`${it.schemaFrom}.${it.name}`] = { to: it.schemaTo, from: it.schemaFrom };
      });
      const viewsPatchedSnap1 = copy(policyPatchedSnap1);
      viewsPatchedSnap1.views = mapEntries(
        viewsPatchedSnap1.views,
        (viewKey, viewValue) => {
          const rename = renamesViewDic[`${viewValue.schema}.${viewValue.name}`];
          const moved = movedViewDic[`${viewValue.schema}.${viewValue.name}`];
          if (rename) {
            viewValue.name = rename.to;
            viewKey = `${viewValue.schema}.${viewValue.name}`;
          }
          if (moved) viewKey = `${moved.to}.${viewValue.name}`;
          return [viewKey, viewValue];
        }
      );
      const diffResult = applyJsonDiff(viewsPatchedSnap1, json22);
      const typedResult = diffResultScheme.parse(diffResult);
      const jsonStatements = [];
      const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
        return preparePgCreateIndexesJson(
          it.name,
          it.schema,
          it.indexes,
          curFull,
          action
        );
      }).flat();
      const jsonDropTables = deletedTables.map((it) => {
        return prepareDropTableJson(it);
      });
      const jsonRenameTables = renamedTables.map((it) => {
        return prepareRenameTableJson(it.from, it.to);
      });
      const alteredTables = typedResult.alteredTablesWithColumns;
      const jsonRenameColumnsStatements = [];
      const jsonDropColumnsStatemets = [];
      const jsonAddColumnsStatemets = [];
      for (let it of columnRenames) {
        jsonRenameColumnsStatements.push(
          ...prepareRenameColumns(it.table, it.schema, it.renames)
        );
      }
      for (let it of columnDeletes) {
        jsonDropColumnsStatemets.push(
          ..._prepareDropColumns(it.table, it.schema, it.columns)
        );
      }
      for (let it of columnCreates) {
        jsonAddColumnsStatemets.push(
          ..._prepareAddColumns(it.table, it.schema, it.columns)
        );
      }
      const jsonAddedCompositePKs = [];
      const jsonDeletedCompositePKs = [];
      const jsonAlteredCompositePKs = [];
      const jsonAddedUniqueConstraints = [];
      const jsonDeletedUniqueConstraints = [];
      const jsonAlteredUniqueConstraints = [];
      const jsonSetTableSchemas = [];
      if (movedTables) {
        for (let it of movedTables) {
          jsonSetTableSchemas.push({
            type: "alter_table_set_schema",
            tableName: it.name,
            schemaFrom: it.schemaFrom || "public",
            schemaTo: it.schemaTo || "public"
          });
        }
      }
      const jsonDeletedCheckConstraints = [];
      const jsonCreatedCheckConstraints = [];
      for (let it of alteredTables) {
        let addedColumns;
        for (const addedPkName of Object.keys(it.addedCompositePKs)) {
          const addedPkColumns = it.addedCompositePKs[addedPkName];
          addedColumns = PgSquasher.unsquashPK(addedPkColumns);
        }
        let deletedColumns;
        for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
          const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
          deletedColumns = PgSquasher.unsquashPK(deletedPkColumns);
        }
        const doPerformDeleteAndCreate = JSON.stringify(addedColumns ?? {}) !== JSON.stringify(deletedColumns ?? {});
        let addedCompositePKs = [];
        let deletedCompositePKs = [];
        let alteredCompositePKs = [];
        if (doPerformDeleteAndCreate) {
          addedCompositePKs = prepareAddCompositePrimaryKeyPg(
            it.name,
            it.schema,
            it.addedCompositePKs,
            curFull
          );
          deletedCompositePKs = prepareDeleteCompositePrimaryKeyPg(
            it.name,
            it.schema,
            it.deletedCompositePKs,
            prevFull
          );
        }
        alteredCompositePKs = prepareAlterCompositePrimaryKeyPg(
          it.name,
          it.schema,
          it.alteredCompositePKs,
          prevFull,
          curFull
        );
        let addedUniqueConstraints = [];
        let deletedUniqueConstraints = [];
        let alteredUniqueConstraints = [];
        let createCheckConstraints = [];
        let deleteCheckConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted2 = {};
          for (const k of Object.keys(it.alteredUniqueConstraints)) {
            added[k] = it.alteredUniqueConstraints[k].__new;
            deleted2[k] = it.alteredUniqueConstraints[k].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted2)
          );
        }
        createCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
        deleteCheckConstraints = prepareDeleteCheckConstraint(
          it.name,
          it.schema,
          it.deletedCheckConstraints
        );
        if (it.alteredCheckConstraints && action !== "push") {
          const added = {};
          const deleted2 = {};
          for (const k of Object.keys(it.alteredCheckConstraints)) {
            added[k] = it.alteredCheckConstraints[k].__new;
            deleted2[k] = it.alteredCheckConstraints[k].__old;
          }
          createCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
          deleteCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted2));
        }
        jsonCreatedCheckConstraints.push(...createCheckConstraints);
        jsonDeletedCheckConstraints.push(...deleteCheckConstraints);
        jsonAddedCompositePKs.push(...addedCompositePKs);
        jsonDeletedCompositePKs.push(...deletedCompositePKs);
        jsonAlteredCompositePKs.push(...alteredCompositePKs);
        jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
        jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
        jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
      }
      const rColumns = jsonRenameColumnsStatements.map((it) => {
        const tableName = it.tableName;
        const schema5 = it.schema;
        return {
          from: { schema: schema5, table: tableName, column: it.oldColumnName },
          to: { schema: schema5, table: tableName, column: it.newColumnName }
        };
      });
      const jsonTableAlternations = alteredTables.map((it) => {
        return preparePgAlterColumns(
          it.name,
          it.schema,
          it.altered,
          json22,
          json1,
          action
        );
      }).flat();
      const jsonCreateIndexesFoAlteredTables = alteredTables.map((it) => {
        return preparePgCreateIndexesJson(
          it.name,
          it.schema,
          it.addedIndexes || {},
          curFull,
          action
        );
      }).flat();
      const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => {
        return prepareDropIndexesJson(
          it.name,
          it.schema,
          it.deletedIndexes || {}
        );
      }).flat();
      const jsonCreatePoliciesStatements = [];
      const jsonDropPoliciesStatements = [];
      const jsonAlterPoliciesStatements = [];
      const jsonRenamePoliciesStatements = [];
      const jsonRenameIndPoliciesStatements = [];
      const jsonCreateIndPoliciesStatements = [];
      const jsonDropIndPoliciesStatements = [];
      const jsonAlterIndPoliciesStatements = [];
      const jsonEnableRLSStatements = [];
      const jsonDisableRLSStatements = [];
      for (let it of indPolicyRenames) {
        jsonRenameIndPoliciesStatements.push(
          ...prepareRenameIndPolicyJsons([it])
        );
      }
      for (const it of indPolicyCreates) {
        jsonCreateIndPoliciesStatements.push(
          ...prepareCreateIndPolicyJsons(
            it.policies
          )
        );
      }
      for (const it of indPolicyDeletes) {
        jsonDropIndPoliciesStatements.push(
          ...prepareDropIndPolicyJsons(
            it.policies
          )
        );
      }
      typedResult.alteredPolicies.forEach(({ values }) => {
        const policy5 = action === "push" ? PgSquasher.unsquashPolicyPush(values) : PgSquasher.unsquashPolicy(values);
        const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(json22.policies[policy5.name].values) : PgSquasher.unsquashPolicy(json22.policies[policy5.name].values);
        const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(json22.policies[policy5.name].values) : PgSquasher.unsquashPolicy(json1.policies[policy5.name].values);
        if (newPolicy.as !== oldPolicy.as) {
          jsonDropIndPoliciesStatements.push(
            ...prepareDropIndPolicyJsons(
              [oldPolicy]
            )
          );
          jsonCreateIndPoliciesStatements.push(
            ...prepareCreateIndPolicyJsons(
              [newPolicy]
            )
          );
          return;
        }
        if (newPolicy.for !== oldPolicy.for) {
          jsonDropIndPoliciesStatements.push(
            ...prepareDropIndPolicyJsons(
              [oldPolicy]
            )
          );
          jsonCreateIndPoliciesStatements.push(
            ...prepareCreateIndPolicyJsons(
              [newPolicy]
            )
          );
          return;
        }
        jsonAlterIndPoliciesStatements.push(
          prepareAlterIndPolicyJson(
            oldPolicy,
            newPolicy
          )
        );
      });
      for (let it of policyRenames) {
        jsonRenamePoliciesStatements.push(
          ...prepareRenamePolicyJsons(it.table, it.schema, it.renames)
        );
      }
      for (const it of policyCreates) {
        jsonCreatePoliciesStatements.push(
          ...prepareCreatePolicyJsons(
            it.table,
            it.schema,
            it.columns
          )
        );
      }
      for (const it of policyDeletes) {
        jsonDropPoliciesStatements.push(
          ...prepareDropPolicyJsons(
            it.table,
            it.schema,
            it.columns
          )
        );
      }
      alteredTables.forEach((it) => {
        Object.keys(it.alteredPolicies).forEach((policyName) => {
          const newPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(it.alteredPolicies[policyName].__new) : PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__new);
          const oldPolicy = action === "push" ? PgSquasher.unsquashPolicyPush(it.alteredPolicies[policyName].__old) : PgSquasher.unsquashPolicy(it.alteredPolicies[policyName].__old);
          if (newPolicy.as !== oldPolicy.as) {
            jsonDropPoliciesStatements.push(
              ...prepareDropPolicyJsons(
                it.name,
                it.schema,
                [oldPolicy]
              )
            );
            jsonCreatePoliciesStatements.push(
              ...prepareCreatePolicyJsons(
                it.name,
                it.schema,
                [newPolicy]
              )
            );
            return;
          }
          if (newPolicy.for !== oldPolicy.for) {
            jsonDropPoliciesStatements.push(
              ...prepareDropPolicyJsons(
                it.name,
                it.schema,
                [oldPolicy]
              )
            );
            jsonCreatePoliciesStatements.push(
              ...prepareCreatePolicyJsons(
                it.name,
                it.schema,
                [newPolicy]
              )
            );
            return;
          }
          jsonAlterPoliciesStatements.push(
            prepareAlterPolicyJson(
              it.name,
              it.schema,
              it.alteredPolicies[policyName].__old,
              it.alteredPolicies[policyName].__new
            )
          );
        });
        for (const table6 of Object.values(json22.tables)) {
          const policiesInCurrentState = Object.keys(table6.policies);
          const tableInPreviousState = columnsPatchedSnap1.tables[`${table6.schema === "" ? "public" : table6.schema}.${table6.name}`];
          const policiesInPreviousState = tableInPreviousState ? Object.keys(tableInPreviousState.policies) : [];
          if (policiesInPreviousState.length === 0 && policiesInCurrentState.length > 0 && !table6.isRLSEnabled) {
            jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table6.name, schema: table6.schema });
          }
          if (policiesInPreviousState.length > 0 && policiesInCurrentState.length === 0 && !table6.isRLSEnabled) {
            jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema });
          }
          const wasRlsEnabled = tableInPreviousState ? tableInPreviousState.isRLSEnabled : false;
          if (table6.isRLSEnabled !== wasRlsEnabled) {
            if (table6.isRLSEnabled) {
              jsonEnableRLSStatements.push({ type: "enable_rls", tableName: table6.name, schema: table6.schema });
            } else if (!table6.isRLSEnabled && policiesInCurrentState.length === 0) {
              jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema });
            }
          }
        }
        for (const table6 of Object.values(columnsPatchedSnap1.tables)) {
          const tableInCurrentState = json22.tables[`${table6.schema === "" ? "public" : table6.schema}.${table6.name}`];
          if (tableInCurrentState === void 0 && !table6.isRLSEnabled) {
            jsonDisableRLSStatements.push({ type: "disable_rls", tableName: table6.name, schema: table6.schema });
          }
        }
        const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__old;
            return current;
          },
          {}
        );
        const createdIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__new;
            return current;
          },
          {}
        );
        jsonCreateIndexesFoAlteredTables.push(
          ...preparePgCreateIndexesJson(
            it.name,
            it.schema,
            createdIndexes || {},
            curFull,
            action
          )
        );
        jsonDropIndexesForAllAlteredTables.push(
          ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
        );
      });
      const jsonCreateReferencesForCreatedTables = createdTables.map((it) => {
        return prepareCreateReferencesJson(it.name, it.schema, it.foreignKeys);
      }).flat();
      const jsonReferencesForAlteredTables = alteredTables.map((it) => {
        const forAdded = prepareCreateReferencesJson(
          it.name,
          it.schema,
          it.addedForeignKeys
        );
        const forAltered = prepareDropReferencesJson(
          it.name,
          it.schema,
          it.deletedForeignKeys
        );
        const alteredFKs = prepareAlterReferencesJson(
          it.name,
          it.schema,
          it.alteredForeignKeys
        );
        return [...forAdded, ...forAltered, ...alteredFKs];
      }).flat();
      const jsonCreatedReferencesForAlteredTables = jsonReferencesForAlteredTables.filter(
        (t) => t.type === "create_reference"
      );
      const jsonDroppedReferencesForAlteredTables = jsonReferencesForAlteredTables.filter(
        (t) => t.type === "delete_reference"
      );
      const createEnums = createdEnums.map((it) => {
        return prepareCreateEnumJson(it.name, it.schema, it.values);
      }) ?? [];
      const dropEnums = deletedEnums.map((it) => {
        return prepareDropEnumJson(it.name, it.schema);
      });
      const moveEnums = movedEnums.map((it) => {
        return prepareMoveEnumJson(it.name, it.schemaFrom, it.schemaTo);
      });
      const renameEnums = renamedEnums.map((it) => {
        return prepareRenameEnumJson(it.from.name, it.to.name, it.to.schema);
      });
      const jsonAlterEnumsWithAddedValues = typedResult.alteredEnums.map((it) => {
        return prepareAddValuesToEnumJson(it.name, it.schema, it.addedValues);
      }).flat() ?? [];
      const jsonAlterEnumsWithDroppedValues = typedResult.alteredEnums.map((it) => {
        return prepareDropEnumValues(it.name, it.schema, it.deletedValues, curFull);
      }).flat() ?? [];
      const createSequences = createdSequences.map((it) => {
        return prepareCreateSequenceJson(it);
      }) ?? [];
      const dropSequences = deletedSequences.map((it) => {
        return prepareDropSequenceJson(it.name, it.schema);
      });
      const moveSequences = movedSequences.map((it) => {
        return prepareMoveSequenceJson(it.name, it.schemaFrom, it.schemaTo);
      });
      const renameSequences = renamedSequences.map((it) => {
        return prepareRenameSequenceJson(it.from.name, it.to.name, it.to.schema);
      });
      const jsonAlterSequences = typedResult.alteredSequences.map((it) => {
        return prepareAlterSequenceJson(it);
      }).flat() ?? [];
      const createRoles = createdRoles.map((it) => {
        return prepareCreateRoleJson(it);
      }) ?? [];
      const dropRoles = deletedRoles.map((it) => {
        return prepareDropRoleJson(it.name);
      });
      const renameRoles = renamedRoles.map((it) => {
        return prepareRenameRoleJson(it.from.name, it.to.name);
      });
      const jsonAlterRoles = typedResult.alteredRoles.map((it) => {
        return prepareAlterRoleJson(it);
      }).flat() ?? [];
      const createSchemas = prepareCreateSchemasJson(
        createdSchemas.map((it) => it.name)
      );
      const renameSchemas = prepareRenameSchemasJson(
        renamedSchemas.map((it) => ({ from: it.from.name, to: it.to.name }))
      );
      const dropSchemas = prepareDeleteSchemasJson(
        deletedSchemas.map((it) => it.name)
      );
      const createTables = createdTables.map((it) => {
        return preparePgCreateTableJson(it, curFull);
      });
      jsonCreatePoliciesStatements.push(...[].concat(
        ...createdTables.map(
          (it) => prepareCreatePolicyJsons(
            it.name,
            it.schema,
            Object.values(it.policies).map(action === "push" ? PgSquasher.unsquashPolicyPush : PgSquasher.unsquashPolicy)
          )
        )
      ));
      const createViews = [];
      const dropViews = [];
      const renameViews = [];
      const alterViews = [];
      createViews.push(
        ...createdViews.filter((it) => !it.isExisting).map((it) => {
          return preparePgCreateViewJson(
            it.name,
            it.schema,
            it.definition,
            it.materialized,
            it.withNoData,
            it.with,
            it.using,
            it.tablespace
          );
        })
      );
      dropViews.push(
        ...deletedViews.filter((it) => !it.isExisting).map((it) => {
          return prepareDropViewJson(it.name, it.schema, it.materialized);
        })
      );
      renameViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[`${it.from.schema}.${it.from.name}`].isExisting).map((it) => {
          return prepareRenameViewJson(it.to.name, it.from.name, it.to.schema, it.to.materialized);
        })
      );
      alterViews.push(
        ...movedViews.filter(
          (it) => !json22.views[`${it.schemaTo}.${it.name}`].isExisting && !json1.views[`${it.schemaFrom}.${it.name}`].isExisting
        ).map((it) => {
          return preparePgAlterViewAlterSchemaJson(
            it.schemaTo,
            it.schemaFrom,
            it.name,
            json22.views[`${it.schemaTo}.${it.name}`].materialized
          );
        })
      );
      const alteredViews = typedResult.alteredViews.filter((it) => !json22.views[`${it.schema}.${it.name}`].isExisting);
      for (const alteredView of alteredViews) {
        const viewKey = `${alteredView.schema}.${alteredView.name}`;
        const { materialized, with: withOption, definition, withNoData, using, tablespace } = json22.views[viewKey];
        if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
          dropViews.push(prepareDropViewJson(alteredView.name, alteredView.schema, materialized));
          createViews.push(
            preparePgCreateViewJson(
              alteredView.name,
              alteredView.schema,
              definition,
              materialized,
              withNoData,
              withOption,
              using,
              tablespace
            )
          );
          continue;
        }
        if (alteredView.addedWithOption) {
          alterViews.push(
            preparePgAlterViewAddWithOptionJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.addedWithOption
            )
          );
        }
        if (alteredView.deletedWithOption) {
          alterViews.push(
            preparePgAlterViewDropWithOptionJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.deletedWithOption
            )
          );
        }
        if (alteredView.addedWith) {
          alterViews.push(
            preparePgAlterViewAddWithOptionJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.addedWith
            )
          );
        }
        if (alteredView.deletedWith) {
          alterViews.push(
            preparePgAlterViewDropWithOptionJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.deletedWith
            )
          );
        }
        if (alteredView.alteredWith) {
          alterViews.push(
            preparePgAlterViewAddWithOptionJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.alteredWith
            )
          );
        }
        if (alteredView.alteredTablespace) {
          alterViews.push(
            preparePgAlterViewAlterTablespaceJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.alteredTablespace.__new
            )
          );
        }
        if (alteredView.alteredUsing) {
          alterViews.push(
            preparePgAlterViewAlterUsingJson(
              alteredView.name,
              alteredView.schema,
              materialized,
              alteredView.alteredUsing.__new
            )
          );
        }
      }
      jsonStatements.push(...createSchemas);
      jsonStatements.push(...renameSchemas);
      jsonStatements.push(...createEnums);
      jsonStatements.push(...moveEnums);
      jsonStatements.push(...renameEnums);
      jsonStatements.push(...jsonAlterEnumsWithAddedValues);
      jsonStatements.push(...createSequences);
      jsonStatements.push(...moveSequences);
      jsonStatements.push(...renameSequences);
      jsonStatements.push(...jsonAlterSequences);
      jsonStatements.push(...renameRoles);
      jsonStatements.push(...dropRoles);
      jsonStatements.push(...createRoles);
      jsonStatements.push(...jsonAlterRoles);
      jsonStatements.push(...createTables);
      jsonStatements.push(...jsonEnableRLSStatements);
      jsonStatements.push(...jsonDisableRLSStatements);
      jsonStatements.push(...dropViews);
      jsonStatements.push(...renameViews);
      jsonStatements.push(...alterViews);
      jsonStatements.push(...jsonDropTables);
      jsonStatements.push(...jsonSetTableSchemas);
      jsonStatements.push(...jsonRenameTables);
      jsonStatements.push(...jsonRenameColumnsStatements);
      jsonStatements.push(...jsonDeletedUniqueConstraints);
      jsonStatements.push(...jsonDeletedCheckConstraints);
      jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
      jsonStatements.push(...jsonAlterEnumsWithDroppedValues);
      jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDeletedCompositePKs);
      jsonStatements.push(...jsonTableAlternations);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAddColumnsStatemets);
      jsonStatements.push(...jsonCreateReferencesForCreatedTables);
      jsonStatements.push(...jsonCreateIndexesForCreatedTables);
      jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
      jsonStatements.push(...jsonCreateIndexesFoAlteredTables);
      jsonStatements.push(...jsonDropColumnsStatemets);
      jsonStatements.push(...jsonAlteredCompositePKs);
      jsonStatements.push(...jsonAddedUniqueConstraints);
      jsonStatements.push(...jsonCreatedCheckConstraints);
      jsonStatements.push(...jsonAlteredUniqueConstraints);
      jsonStatements.push(...createViews);
      jsonStatements.push(...jsonRenamePoliciesStatements);
      jsonStatements.push(...jsonDropPoliciesStatements);
      jsonStatements.push(...jsonCreatePoliciesStatements);
      jsonStatements.push(...jsonAlterPoliciesStatements);
      jsonStatements.push(...jsonRenameIndPoliciesStatements);
      jsonStatements.push(...jsonDropIndPoliciesStatements);
      jsonStatements.push(...jsonCreateIndPoliciesStatements);
      jsonStatements.push(...jsonAlterIndPoliciesStatements);
      jsonStatements.push(...dropEnums);
      jsonStatements.push(...dropSequences);
      jsonStatements.push(...dropSchemas);
      const filteredJsonStatements = jsonStatements.filter((st) => {
        if (st.type === "alter_table_alter_column_drop_notnull") {
          if (jsonStatements.find(
            (it) => it.type === "alter_table_alter_column_drop_identity" && it.tableName === st.tableName && it.schema === st.schema
          )) {
            return false;
          }
        }
        if (st.type === "alter_table_alter_column_set_notnull") {
          if (jsonStatements.find(
            (it) => it.type === "alter_table_alter_column_set_identity" && it.tableName === st.tableName && it.schema === st.schema
          )) {
            return false;
          }
        }
        return true;
      });
      const filteredEnumsJsonStatements = filteredJsonStatements.filter((st) => {
        if (st.type === "alter_type_add_value") {
          if (filteredJsonStatements.find(
            (it) => it.type === "alter_type_drop_value" && it.name === st.name && it.enumSchema === st.schema
          )) {
            return false;
          }
        }
        return true;
      });
      const filteredEnums2JsonStatements = filteredEnumsJsonStatements.filter((st) => {
        if (st.type === "alter_table_alter_column_set_default") {
          if (filteredEnumsJsonStatements.find(
            (it) => it.type === "pg_alter_table_alter_column_set_type" && it.columnDefault === st.newDefaultValue && it.columnName === st.columnName && it.tableName === st.tableName && it.schema === st.schema
          )) {
            return false;
          }
          if (filteredEnumsJsonStatements.find(
            (it) => it.type === "alter_type_drop_value" && it.columnsWithEnum.find(
              (column6) => column6.default === st.newDefaultValue && column6.column === st.columnName && column6.table === st.tableName && column6.tableSchema === st.schema
            )
          )) {
            return false;
          }
        }
        return true;
      });
      const sqlStatements = fromJson(filteredEnums2JsonStatements, "postgresql", action);
      const uniqueSqlStatements = [];
      sqlStatements.forEach((ss) => {
        if (!uniqueSqlStatements.includes(ss)) {
          uniqueSqlStatements.push(ss);
        }
      });
      const rSchemas = renamedSchemas.map((it) => ({
        from: it.from.name,
        to: it.to.name
      }));
      const rTables = renamedTables.map((it) => {
        return { from: it.from, to: it.to };
      });
      const _meta = prepareMigrationMeta(rSchemas, rTables, rColumns);
      return {
        statements: filteredEnums2JsonStatements,
        sqlStatements: uniqueSqlStatements,
        _meta
      };
    };
    applyMysqlSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
      for (const tableName in json1.tables) {
        const table6 = json1.tables[tableName];
        for (const indexName2 in table6.indexes) {
          const index6 = MySqlSquasher.unsquashIdx(table6.indexes[indexName2]);
          if (index6.isUnique) {
            table6.uniqueConstraints[indexName2] = MySqlSquasher.squashUnique({
              name: index6.name,
              columns: index6.columns
            });
            delete json1.tables[tableName].indexes[index6.name];
          }
        }
      }
      for (const tableName in json22.tables) {
        const table6 = json22.tables[tableName];
        for (const indexName2 in table6.indexes) {
          const index6 = MySqlSquasher.unsquashIdx(table6.indexes[indexName2]);
          if (index6.isUnique) {
            table6.uniqueConstraints[indexName2] = MySqlSquasher.squashUnique({
              name: index6.name,
              columns: index6.columns
            });
            delete json22.tables[tableName].indexes[index6.name];
          }
        }
      }
      const tablesDiff = diffSchemasOrTables(json1.tables, json22.tables);
      const {
        created: createdTables,
        deleted: deletedTables,
        renamed: renamedTables
        // renamed or moved
      } = await tablesResolver2({
        created: tablesDiff.added,
        deleted: tablesDiff.deleted
      });
      const tablesPatchedSnap1 = copy(json1);
      tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_2, it) => {
        const { name: name2 } = nameChangeFor(it, renamedTables);
        it.name = name2;
        return [name2, it];
      });
      const res = diffColumns(tablesPatchedSnap1.tables, json22.tables);
      const columnRenames = [];
      const columnCreates = [];
      const columnDeletes = [];
      for (let entry of Object.values(res)) {
        const { renamed, created, deleted } = await columnsResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.columns.deleted,
          created: entry.columns.added
        });
        if (created.length > 0) {
          columnCreates.push({
            table: entry.name,
            columns: created
          });
        }
        if (deleted.length > 0) {
          columnDeletes.push({
            table: entry.name,
            columns: deleted
          });
        }
        if (renamed.length > 0) {
          columnRenames.push({
            table: entry.name,
            renames: renamed
          });
        }
      }
      const columnRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[it.table] = it.renames;
          return acc;
        },
        {}
      );
      const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
      columnsPatchedSnap1.tables = mapEntries(
        columnsPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapKeys(
            tableValue.columns,
            (columnKey, column6) => {
              const rens = columnRenamesDict[tableValue.name] || [];
              const newName = columnChangeFor(columnKey, rens);
              column6.name = newName;
              return newName;
            }
          );
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const viewsDiff = diffSchemasOrTables(json1.views, json22.views);
      const {
        created: createdViews,
        deleted: deletedViews,
        renamed: renamedViews
        // renamed or moved
      } = await viewsResolver2({
        created: viewsDiff.added,
        deleted: viewsDiff.deleted
      });
      const renamesViewDic = {};
      renamedViews.forEach((it) => {
        renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
      });
      const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
      viewsPatchedSnap1.views = mapEntries(
        viewsPatchedSnap1.views,
        (viewKey, viewValue) => {
          const rename = renamesViewDic[viewValue.name];
          if (rename) {
            viewValue.name = rename.to;
            viewKey = rename.to;
          }
          return [viewKey, viewValue];
        }
      );
      const diffResult = applyJsonDiff(viewsPatchedSnap1, json22);
      const typedResult = diffResultSchemeMysql.parse(diffResult);
      const jsonStatements = [];
      const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.indexes,
          curFull.internal
        );
      }).flat();
      const jsonDropTables = deletedTables.map((it) => {
        return prepareDropTableJson(it);
      });
      const jsonRenameTables = renamedTables.map((it) => {
        return prepareRenameTableJson(it.from, it.to);
      });
      const alteredTables = typedResult.alteredTablesWithColumns;
      const jsonAddedCompositePKs = [];
      const jsonDeletedCompositePKs = [];
      const jsonAlteredCompositePKs = [];
      const jsonAddedUniqueConstraints = [];
      const jsonDeletedUniqueConstraints = [];
      const jsonAlteredUniqueConstraints = [];
      const jsonCreatedCheckConstraints = [];
      const jsonDeletedCheckConstraints = [];
      const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
      const jsonAddColumnsStatemets = columnCreates.map((it) => _prepareAddColumns(it.table, "", it.columns)).flat();
      const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
      alteredTables.forEach((it) => {
        let addedColumns = [];
        for (const addedPkName of Object.keys(it.addedCompositePKs)) {
          const addedPkColumns = it.addedCompositePKs[addedPkName];
          addedColumns = MySqlSquasher.unsquashPK(addedPkColumns).columns;
        }
        let deletedColumns = [];
        for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
          const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
          deletedColumns = MySqlSquasher.unsquashPK(deletedPkColumns).columns;
        }
        const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
        let addedCompositePKs = [];
        let deletedCompositePKs = [];
        let alteredCompositePKs = [];
        addedCompositePKs = prepareAddCompositePrimaryKeyMySql(
          it.name,
          it.addedCompositePKs,
          prevFull,
          curFull
        );
        deletedCompositePKs = prepareDeleteCompositePrimaryKeyMySql(
          it.name,
          it.deletedCompositePKs,
          prevFull
        );
        alteredCompositePKs = prepareAlterCompositePrimaryKeyMySql(
          it.name,
          it.alteredCompositePKs,
          prevFull,
          curFull
        );
        let addedUniqueConstraints = [];
        let deletedUniqueConstraints = [];
        let alteredUniqueConstraints = [];
        let createdCheckConstraints = [];
        let deletedCheckConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted = {};
          for (const k of Object.keys(it.alteredUniqueConstraints)) {
            added[k] = it.alteredUniqueConstraints[k].__new;
            deleted[k] = it.alteredUniqueConstraints[k].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
          );
        }
        createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
        deletedCheckConstraints = prepareDeleteCheckConstraint(
          it.name,
          it.schema,
          it.deletedCheckConstraints
        );
        if (it.alteredCheckConstraints && action !== "push") {
          const added = {};
          const deleted = {};
          for (const k of Object.keys(it.alteredCheckConstraints)) {
            added[k] = it.alteredCheckConstraints[k].__new;
            deleted[k] = it.alteredCheckConstraints[k].__old;
          }
          createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
          deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
        }
        jsonAddedCompositePKs.push(...addedCompositePKs);
        jsonDeletedCompositePKs.push(...deletedCompositePKs);
        jsonAlteredCompositePKs.push(...alteredCompositePKs);
        jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
        jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
        jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
        jsonCreatedCheckConstraints.push(...createdCheckConstraints);
        jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
      });
      const rColumns = jsonRenameColumnsStatements.map((it) => {
        const tableName = it.tableName;
        const schema5 = it.schema;
        return {
          from: { schema: schema5, table: tableName, column: it.oldColumnName },
          to: { schema: schema5, table: tableName, column: it.newColumnName }
        };
      });
      const jsonTableAlternations = alteredTables.map((it) => {
        return prepareAlterColumnsMysql(
          it.name,
          it.schema,
          it.altered,
          json1,
          json22,
          action
        );
      }).flat();
      const jsonCreateIndexesForAllAlteredTables = alteredTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.addedIndexes || {},
          curFull.internal
        );
      }).flat();
      const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => {
        return prepareDropIndexesJson(
          it.name,
          it.schema,
          it.deletedIndexes || {}
        );
      }).flat();
      alteredTables.forEach((it) => {
        const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__old;
            return current;
          },
          {}
        );
        const createdIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__new;
            return current;
          },
          {}
        );
        jsonCreateIndexesForAllAlteredTables.push(
          ...prepareCreateIndexesJson(it.name, it.schema, createdIndexes || {})
        );
        jsonDropIndexesForAllAlteredTables.push(
          ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
        );
      });
      const jsonCreateReferencesForCreatedTables = createdTables.map((it) => {
        return prepareCreateReferencesJson(it.name, it.schema, it.foreignKeys);
      }).flat();
      const jsonReferencesForAllAlteredTables = alteredTables.map((it) => {
        const forAdded = prepareCreateReferencesJson(
          it.name,
          it.schema,
          it.addedForeignKeys
        );
        const forAltered = prepareDropReferencesJson(
          it.name,
          it.schema,
          it.deletedForeignKeys
        );
        const alteredFKs = prepareAlterReferencesJson(
          it.name,
          it.schema,
          it.alteredForeignKeys
        );
        return [...forAdded, ...forAltered, ...alteredFKs];
      }).flat();
      const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t) => t.type === "create_reference"
      );
      const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t) => t.type === "delete_reference"
      );
      const jsonMySqlCreateTables = createdTables.map((it) => {
        return prepareMySqlCreateTableJson(
          it,
          curFull,
          curFull.internal
        );
      });
      const createViews = [];
      const dropViews = [];
      const renameViews = [];
      const alterViews = [];
      createViews.push(
        ...createdViews.filter((it) => !it.isExisting).map((it) => {
          return prepareMySqlCreateViewJson(
            it.name,
            it.definition,
            it.meta
          );
        })
      );
      dropViews.push(
        ...deletedViews.filter((it) => !it.isExisting).map((it) => {
          return prepareDropViewJson(it.name);
        })
      );
      renameViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting && !json1.views[it.from.name].isExisting).map((it) => {
          return prepareRenameViewJson(it.to.name, it.from.name);
        })
      );
      const alteredViews = typedResult.alteredViews.filter((it) => !json22.views[it.name].isExisting);
      for (const alteredView of alteredViews) {
        const { definition, meta } = json22.views[alteredView.name];
        if (alteredView.alteredExisting) {
          dropViews.push(prepareDropViewJson(alteredView.name));
          createViews.push(
            prepareMySqlCreateViewJson(
              alteredView.name,
              definition,
              meta
            )
          );
          continue;
        }
        if (alteredView.alteredDefinition && action !== "push") {
          createViews.push(
            prepareMySqlCreateViewJson(
              alteredView.name,
              definition,
              meta,
              true
            )
          );
          continue;
        }
        if (alteredView.alteredMeta) {
          const view5 = curFull["views"][alteredView.name];
          alterViews.push(
            prepareMySqlAlterView(view5)
          );
        }
      }
      jsonStatements.push(...jsonMySqlCreateTables);
      jsonStatements.push(...jsonDropTables);
      jsonStatements.push(...jsonRenameTables);
      jsonStatements.push(...jsonRenameColumnsStatements);
      jsonStatements.push(...dropViews);
      jsonStatements.push(...renameViews);
      jsonStatements.push(...alterViews);
      jsonStatements.push(...jsonDeletedUniqueConstraints);
      jsonStatements.push(...jsonDeletedCheckConstraints);
      jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
      jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDeletedCompositePKs);
      jsonStatements.push(...jsonTableAlternations);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAddColumnsStatemets);
      jsonStatements.push(...jsonAddedUniqueConstraints);
      jsonStatements.push(...jsonDeletedUniqueConstraints);
      jsonStatements.push(...jsonCreateReferencesForCreatedTables);
      jsonStatements.push(...jsonCreateIndexesForCreatedTables);
      jsonStatements.push(...jsonCreatedCheckConstraints);
      jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
      jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDropColumnsStatemets);
      jsonStatements.push(...jsonAlteredCompositePKs);
      jsonStatements.push(...createViews);
      jsonStatements.push(...jsonAlteredUniqueConstraints);
      const sqlStatements = fromJson(jsonStatements, "mysql");
      const uniqueSqlStatements = [];
      sqlStatements.forEach((ss) => {
        if (!uniqueSqlStatements.includes(ss)) {
          uniqueSqlStatements.push(ss);
        }
      });
      const rTables = renamedTables.map((it) => {
        return { from: it.from, to: it.to };
      });
      const _meta = prepareMigrationMeta([], rTables, rColumns);
      return {
        statements: jsonStatements,
        sqlStatements: uniqueSqlStatements,
        _meta
      };
    };
    applySingleStoreSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, prevFull, curFull, action) => {
      for (const tableName in json1.tables) {
        const table6 = json1.tables[tableName];
        for (const indexName2 in table6.indexes) {
          const index6 = SingleStoreSquasher.unsquashIdx(table6.indexes[indexName2]);
          if (index6.isUnique) {
            table6.uniqueConstraints[indexName2] = SingleStoreSquasher.squashUnique({
              name: index6.name,
              columns: index6.columns
            });
            delete json1.tables[tableName].indexes[index6.name];
          }
        }
      }
      for (const tableName in json22.tables) {
        const table6 = json22.tables[tableName];
        for (const indexName2 in table6.indexes) {
          const index6 = SingleStoreSquasher.unsquashIdx(table6.indexes[indexName2]);
          if (index6.isUnique) {
            table6.uniqueConstraints[indexName2] = SingleStoreSquasher.squashUnique({
              name: index6.name,
              columns: index6.columns
            });
            delete json22.tables[tableName].indexes[index6.name];
          }
        }
      }
      const tablesDiff = diffSchemasOrTables(json1.tables, json22.tables);
      const {
        created: createdTables,
        deleted: deletedTables,
        renamed: renamedTables
        // renamed or moved
      } = await tablesResolver2({
        created: tablesDiff.added,
        deleted: tablesDiff.deleted
      });
      const tablesPatchedSnap1 = copy(json1);
      tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_2, it) => {
        const { name: name2 } = nameChangeFor(it, renamedTables);
        it.name = name2;
        return [name2, it];
      });
      const res = diffColumns(tablesPatchedSnap1.tables, json22.tables);
      const columnRenames = [];
      const columnCreates = [];
      const columnDeletes = [];
      for (let entry of Object.values(res)) {
        const { renamed, created, deleted } = await columnsResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.columns.deleted,
          created: entry.columns.added
        });
        if (created.length > 0) {
          columnCreates.push({
            table: entry.name,
            columns: created
          });
        }
        if (deleted.length > 0) {
          columnDeletes.push({
            table: entry.name,
            columns: deleted
          });
        }
        if (renamed.length > 0) {
          columnRenames.push({
            table: entry.name,
            renames: renamed
          });
        }
      }
      const columnRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[it.table] = it.renames;
          return acc;
        },
        {}
      );
      const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
      columnsPatchedSnap1.tables = mapEntries(
        columnsPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapKeys(
            tableValue.columns,
            (columnKey, column6) => {
              const rens = columnRenamesDict[tableValue.name] || [];
              const newName = columnChangeFor(columnKey, rens);
              column6.name = newName;
              return newName;
            }
          );
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const diffResult = applyJsonDiff(columnsPatchedSnap1, json22);
      const typedResult = diffResultSchemeSingleStore.parse(diffResult);
      const jsonStatements = [];
      const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.indexes,
          curFull.internal
        );
      }).flat();
      const jsonDropTables = deletedTables.map((it) => {
        return prepareDropTableJson(it);
      });
      const jsonRenameTables = renamedTables.map((it) => {
        return prepareRenameTableJson(it.from, it.to);
      });
      const alteredTables = typedResult.alteredTablesWithColumns;
      const jsonAddedCompositePKs = [];
      const jsonAddedUniqueConstraints = [];
      const jsonDeletedUniqueConstraints = [];
      const jsonAlteredUniqueConstraints = [];
      const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
      const jsonAddColumnsStatemets = columnCreates.map((it) => _prepareAddColumns(it.table, "", it.columns)).flat();
      const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
      alteredTables.forEach((it) => {
        let addedColumns = [];
        for (const addedPkName of Object.keys(it.addedCompositePKs)) {
          const addedPkColumns = it.addedCompositePKs[addedPkName];
          addedColumns = SingleStoreSquasher.unsquashPK(addedPkColumns).columns;
        }
        let deletedColumns = [];
        for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
          const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
          deletedColumns = SingleStoreSquasher.unsquashPK(deletedPkColumns).columns;
        }
        const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
        let addedUniqueConstraints = [];
        let deletedUniqueConstraints = [];
        let alteredUniqueConstraints = [];
        let createdCheckConstraints = [];
        let deletedCheckConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted = {};
          for (const k of Object.keys(it.alteredUniqueConstraints)) {
            added[k] = it.alteredUniqueConstraints[k].__new;
            deleted[k] = it.alteredUniqueConstraints[k].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
          );
        }
        createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
        deletedCheckConstraints = prepareDeleteCheckConstraint(
          it.name,
          it.schema,
          it.deletedCheckConstraints
        );
        if (it.alteredCheckConstraints && action !== "push") {
          const added = {};
          const deleted = {};
          for (const k of Object.keys(it.alteredCheckConstraints)) {
            added[k] = it.alteredCheckConstraints[k].__new;
            deleted[k] = it.alteredCheckConstraints[k].__old;
          }
          createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
          deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
        }
        jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
        jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
        jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
      });
      const rColumns = jsonRenameColumnsStatements.map((it) => {
        const tableName = it.tableName;
        const schema5 = it.schema;
        return {
          from: { schema: schema5, table: tableName, column: it.oldColumnName },
          to: { schema: schema5, table: tableName, column: it.newColumnName }
        };
      });
      const jsonTableAlternations = alteredTables.map((it) => {
        return prepareAlterColumnsMysql(
          it.name,
          it.schema,
          it.altered,
          json1,
          json22,
          action
        );
      }).flat();
      const jsonCreateIndexesForAllAlteredTables = alteredTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.addedIndexes || {},
          curFull.internal
        );
      }).flat();
      const jsonDropIndexesForAllAlteredTables = alteredTables.map((it) => {
        return prepareDropIndexesJson(
          it.name,
          it.schema,
          it.deletedIndexes || {}
        );
      }).flat();
      alteredTables.forEach((it) => {
        const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__old;
            return current;
          },
          {}
        );
        const createdIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__new;
            return current;
          },
          {}
        );
        jsonCreateIndexesForAllAlteredTables.push(
          ...prepareCreateIndexesJson(it.name, it.schema, createdIndexes || {})
        );
        jsonDropIndexesForAllAlteredTables.push(
          ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
        );
      });
      const jsonSingleStoreCreateTables = createdTables.map((it) => {
        return prepareSingleStoreCreateTableJson(
          it,
          curFull,
          curFull.internal
        );
      });
      jsonStatements.push(...jsonSingleStoreCreateTables);
      jsonStatements.push(...jsonDropTables);
      jsonStatements.push(...jsonRenameTables);
      jsonStatements.push(...jsonRenameColumnsStatements);
      jsonStatements.push(...jsonDeletedUniqueConstraints);
      jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
      jsonStatements.push(...jsonTableAlternations);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAddedUniqueConstraints);
      jsonStatements.push(...jsonDeletedUniqueConstraints);
      jsonStatements.push(...jsonAddColumnsStatemets);
      jsonStatements.push(...jsonCreateIndexesForCreatedTables);
      jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDropColumnsStatemets);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAlteredUniqueConstraints);
      const combinedJsonStatements = singleStoreCombineStatements(jsonStatements, json22);
      const sqlStatements = fromJson(combinedJsonStatements, "singlestore");
      const uniqueSqlStatements = [];
      sqlStatements.forEach((ss) => {
        if (!uniqueSqlStatements.includes(ss)) {
          uniqueSqlStatements.push(ss);
        }
      });
      const rTables = renamedTables.map((it) => {
        return { from: it.from, to: it.to };
      });
      const _meta = prepareMigrationMeta([], rTables, rColumns);
      return {
        statements: combinedJsonStatements,
        sqlStatements: uniqueSqlStatements,
        _meta
      };
    };
    applySqliteSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
      const tablesDiff = diffSchemasOrTables(json1.tables, json22.tables);
      const {
        created: createdTables,
        deleted: deletedTables,
        renamed: renamedTables
      } = await tablesResolver2({
        created: tablesDiff.added,
        deleted: tablesDiff.deleted
      });
      const tablesPatchedSnap1 = copy(json1);
      tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_2, it) => {
        const { name: name2 } = nameChangeFor(it, renamedTables);
        it.name = name2;
        return [name2, it];
      });
      const res = diffColumns(tablesPatchedSnap1.tables, json22.tables);
      const columnRenames = [];
      const columnCreates = [];
      const columnDeletes = [];
      for (let entry of Object.values(res)) {
        const { renamed, created, deleted } = await columnsResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.columns.deleted,
          created: entry.columns.added
        });
        if (created.length > 0) {
          columnCreates.push({
            table: entry.name,
            columns: created
          });
        }
        if (deleted.length > 0) {
          columnDeletes.push({
            table: entry.name,
            columns: deleted
          });
        }
        if (renamed.length > 0) {
          columnRenames.push({
            table: entry.name,
            renames: renamed
          });
        }
      }
      const columnRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[it.table] = it.renames;
          return acc;
        },
        {}
      );
      const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
      columnsPatchedSnap1.tables = mapEntries(
        columnsPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapKeys(
            tableValue.columns,
            (columnKey, column6) => {
              const rens = columnRenamesDict[tableValue.name] || [];
              const newName = columnChangeFor(columnKey, rens);
              column6.name = newName;
              return newName;
            }
          );
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const viewsDiff = diffSchemasOrTables(json1.views, json22.views);
      const {
        created: createdViews,
        deleted: deletedViews,
        renamed: renamedViews
        // renamed or moved
      } = await viewsResolver2({
        created: viewsDiff.added,
        deleted: viewsDiff.deleted
      });
      const renamesViewDic = {};
      renamedViews.forEach((it) => {
        renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
      });
      const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
      viewsPatchedSnap1.views = mapEntries(
        viewsPatchedSnap1.views,
        (viewKey, viewValue) => {
          const rename = renamesViewDic[viewValue.name];
          if (rename) {
            viewValue.name = rename.to;
          }
          return [viewKey, viewValue];
        }
      );
      const diffResult = applyJsonDiff(viewsPatchedSnap1, json22);
      const typedResult = diffResultSchemeSQLite.parse(diffResult);
      const tablesMap = {};
      typedResult.alteredTablesWithColumns.forEach((obj) => {
        tablesMap[obj.name] = obj;
      });
      const jsonCreateTables = createdTables.map((it) => {
        return prepareSQLiteCreateTable(it, action);
      });
      const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.indexes,
          curFull.internal
        );
      }).flat();
      const jsonDropTables = deletedTables.map((it) => {
        return prepareDropTableJson(it);
      });
      const jsonRenameTables = renamedTables.map((it) => {
        return prepareRenameTableJson(it.from, it.to);
      });
      const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
      const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
      const jsonAddColumnsStatemets = columnCreates.map((it) => {
        return _prepareSqliteAddColumns(
          it.table,
          it.columns,
          tablesMap[it.table] && tablesMap[it.table].addedForeignKeys ? Object.values(tablesMap[it.table].addedForeignKeys) : []
        );
      }).flat();
      const allAltered = typedResult.alteredTablesWithColumns;
      const jsonAddedCompositePKs = [];
      const jsonDeletedCompositePKs = [];
      const jsonAlteredCompositePKs = [];
      const jsonAddedUniqueConstraints = [];
      const jsonDeletedUniqueConstraints = [];
      const jsonAlteredUniqueConstraints = [];
      const jsonDeletedCheckConstraints = [];
      const jsonCreatedCheckConstraints = [];
      allAltered.forEach((it) => {
        let addedColumns = [];
        for (const addedPkName of Object.keys(it.addedCompositePKs)) {
          const addedPkColumns = it.addedCompositePKs[addedPkName];
          addedColumns = SQLiteSquasher.unsquashPK(addedPkColumns);
        }
        let deletedColumns = [];
        for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
          const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
          deletedColumns = SQLiteSquasher.unsquashPK(deletedPkColumns);
        }
        const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
        let addedCompositePKs = [];
        let deletedCompositePKs = [];
        let alteredCompositePKs = [];
        if (doPerformDeleteAndCreate) {
          addedCompositePKs = prepareAddCompositePrimaryKeySqlite(
            it.name,
            it.addedCompositePKs
          );
          deletedCompositePKs = prepareDeleteCompositePrimaryKeySqlite(
            it.name,
            it.deletedCompositePKs
          );
        }
        alteredCompositePKs = prepareAlterCompositePrimaryKeySqlite(
          it.name,
          it.alteredCompositePKs
        );
        let addedUniqueConstraints = [];
        let deletedUniqueConstraints = [];
        let alteredUniqueConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted = {};
          for (const k of Object.keys(it.alteredUniqueConstraints)) {
            added[k] = it.alteredUniqueConstraints[k].__new;
            deleted[k] = it.alteredUniqueConstraints[k].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
          );
        }
        let createdCheckConstraints = [];
        let deletedCheckConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted = {};
          for (const k of Object.keys(it.alteredUniqueConstraints)) {
            added[k] = it.alteredUniqueConstraints[k].__new;
            deleted[k] = it.alteredUniqueConstraints[k].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
          );
        }
        createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
        deletedCheckConstraints = prepareDeleteCheckConstraint(
          it.name,
          it.schema,
          it.deletedCheckConstraints
        );
        if (it.alteredCheckConstraints && action !== "push") {
          const added = {};
          const deleted = {};
          for (const k of Object.keys(it.alteredCheckConstraints)) {
            added[k] = it.alteredCheckConstraints[k].__new;
            deleted[k] = it.alteredCheckConstraints[k].__old;
          }
          createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
          deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
        }
        jsonAddedCompositePKs.push(...addedCompositePKs);
        jsonDeletedCompositePKs.push(...deletedCompositePKs);
        jsonAlteredCompositePKs.push(...alteredCompositePKs);
        jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
        jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
        jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
        jsonCreatedCheckConstraints.push(...createdCheckConstraints);
        jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
      });
      const rColumns = jsonRenameColumnsStatements.map((it) => {
        const tableName = it.tableName;
        const schema5 = it.schema;
        return {
          from: { schema: schema5, table: tableName, column: it.oldColumnName },
          to: { schema: schema5, table: tableName, column: it.newColumnName }
        };
      });
      const jsonTableAlternations = allAltered.map((it) => {
        return prepareSqliteAlterColumns(it.name, it.schema, it.altered, json22);
      }).flat();
      const jsonCreateIndexesForAllAlteredTables = allAltered.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.addedIndexes || {},
          curFull.internal
        );
      }).flat();
      const jsonDropIndexesForAllAlteredTables = allAltered.map((it) => {
        return prepareDropIndexesJson(
          it.name,
          it.schema,
          it.deletedIndexes || {}
        );
      }).flat();
      allAltered.forEach((it) => {
        const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__old;
            return current;
          },
          {}
        );
        const createdIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__new;
            return current;
          },
          {}
        );
        jsonCreateIndexesForAllAlteredTables.push(
          ...prepareCreateIndexesJson(
            it.name,
            it.schema,
            createdIndexes || {},
            curFull.internal
          )
        );
        jsonDropIndexesForAllAlteredTables.push(
          ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
        );
      });
      const jsonReferencesForAllAlteredTables = allAltered.map((it) => {
        const forAdded = prepareCreateReferencesJson(
          it.name,
          it.schema,
          it.addedForeignKeys
        );
        const forAltered = prepareDropReferencesJson(
          it.name,
          it.schema,
          it.deletedForeignKeys
        );
        const alteredFKs = prepareAlterReferencesJson(
          it.name,
          it.schema,
          it.alteredForeignKeys
        );
        return [...forAdded, ...forAltered, ...alteredFKs];
      }).flat();
      const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t) => t.type === "create_reference"
      );
      const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t) => t.type === "delete_reference"
      );
      const createViews = [];
      const dropViews = [];
      createViews.push(
        ...createdViews.filter((it) => !it.isExisting).map((it) => {
          return prepareSqliteCreateViewJson(
            it.name,
            it.definition
          );
        })
      );
      dropViews.push(
        ...deletedViews.filter((it) => !it.isExisting).map((it) => {
          return prepareDropViewJson(it.name);
        })
      );
      dropViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
          return prepareDropViewJson(it.from.name);
        })
      );
      createViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
          return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
        })
      );
      const alteredViews = typedResult.alteredViews.filter((it) => !json22.views[it.name].isExisting);
      for (const alteredView of alteredViews) {
        const { definition } = json22.views[alteredView.name];
        if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
          dropViews.push(prepareDropViewJson(alteredView.name));
          createViews.push(
            prepareSqliteCreateViewJson(
              alteredView.name,
              definition
            )
          );
        }
      }
      const jsonStatements = [];
      jsonStatements.push(...jsonCreateTables);
      jsonStatements.push(...jsonDropTables);
      jsonStatements.push(...jsonRenameTables);
      jsonStatements.push(...jsonRenameColumnsStatements);
      jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
      jsonStatements.push(...jsonDeletedCheckConstraints);
      jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDeletedCompositePKs);
      jsonStatements.push(...jsonTableAlternations);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAddColumnsStatemets);
      jsonStatements.push(...jsonCreateIndexesForCreatedTables);
      jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
      jsonStatements.push(...jsonCreatedCheckConstraints);
      jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
      jsonStatements.push(...jsonDropColumnsStatemets);
      jsonStatements.push(...jsonAlteredCompositePKs);
      jsonStatements.push(...jsonAlteredUniqueConstraints);
      jsonStatements.push(...dropViews);
      jsonStatements.push(...createViews);
      const combinedJsonStatements = sqliteCombineStatements(jsonStatements, json22, action);
      const sqlStatements = fromJson(combinedJsonStatements, "sqlite");
      const uniqueSqlStatements = [];
      sqlStatements.forEach((ss) => {
        if (!uniqueSqlStatements.includes(ss)) {
          uniqueSqlStatements.push(ss);
        }
      });
      const rTables = renamedTables.map((it) => {
        return { from: it.from, to: it.to };
      });
      const _meta = prepareMigrationMeta([], rTables, rColumns);
      return {
        statements: combinedJsonStatements,
        sqlStatements: uniqueSqlStatements,
        _meta
      };
    };
    applyLibSQLSnapshotsDiff = async (json1, json22, tablesResolver2, columnsResolver2, viewsResolver2, prevFull, curFull, action) => {
      const tablesDiff = diffSchemasOrTables(json1.tables, json22.tables);
      const {
        created: createdTables,
        deleted: deletedTables,
        renamed: renamedTables
      } = await tablesResolver2({
        created: tablesDiff.added,
        deleted: tablesDiff.deleted
      });
      const tablesPatchedSnap1 = copy(json1);
      tablesPatchedSnap1.tables = mapEntries(tablesPatchedSnap1.tables, (_2, it) => {
        const { name: name2 } = nameChangeFor(it, renamedTables);
        it.name = name2;
        return [name2, it];
      });
      const res = diffColumns(tablesPatchedSnap1.tables, json22.tables);
      const columnRenames = [];
      const columnCreates = [];
      const columnDeletes = [];
      for (let entry of Object.values(res)) {
        const { renamed, created, deleted } = await columnsResolver2({
          tableName: entry.name,
          schema: entry.schema,
          deleted: entry.columns.deleted,
          created: entry.columns.added
        });
        if (created.length > 0) {
          columnCreates.push({
            table: entry.name,
            columns: created
          });
        }
        if (deleted.length > 0) {
          columnDeletes.push({
            table: entry.name,
            columns: deleted
          });
        }
        if (renamed.length > 0) {
          columnRenames.push({
            table: entry.name,
            renames: renamed
          });
        }
      }
      const columnRenamesDict = columnRenames.reduce(
        (acc, it) => {
          acc[it.table] = it.renames;
          return acc;
        },
        {}
      );
      const columnsPatchedSnap1 = copy(tablesPatchedSnap1);
      columnsPatchedSnap1.tables = mapEntries(
        columnsPatchedSnap1.tables,
        (tableKey2, tableValue) => {
          const patchedColumns = mapKeys(
            tableValue.columns,
            (columnKey, column6) => {
              const rens = columnRenamesDict[tableValue.name] || [];
              const newName = columnChangeFor(columnKey, rens);
              column6.name = newName;
              return newName;
            }
          );
          tableValue.columns = patchedColumns;
          return [tableKey2, tableValue];
        }
      );
      const viewsDiff = diffSchemasOrTables(json1.views, json22.views);
      const {
        created: createdViews,
        deleted: deletedViews,
        renamed: renamedViews
        // renamed or moved
      } = await viewsResolver2({
        created: viewsDiff.added,
        deleted: viewsDiff.deleted
      });
      const renamesViewDic = {};
      renamedViews.forEach((it) => {
        renamesViewDic[it.from.name] = { to: it.to.name, from: it.from.name };
      });
      const viewsPatchedSnap1 = copy(columnsPatchedSnap1);
      viewsPatchedSnap1.views = mapEntries(
        viewsPatchedSnap1.views,
        (viewKey, viewValue) => {
          const rename = renamesViewDic[viewValue.name];
          if (rename) {
            viewValue.name = rename.to;
          }
          return [viewKey, viewValue];
        }
      );
      const diffResult = applyJsonDiff(viewsPatchedSnap1, json22);
      const typedResult = diffResultSchemeSQLite.parse(diffResult);
      const tablesMap = {};
      typedResult.alteredTablesWithColumns.forEach((obj) => {
        tablesMap[obj.name] = obj;
      });
      const jsonCreateTables = createdTables.map((it) => {
        return prepareSQLiteCreateTable(it, action);
      });
      const jsonCreateIndexesForCreatedTables = createdTables.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.indexes,
          curFull.internal
        );
      }).flat();
      const jsonDropTables = deletedTables.map((it) => {
        return prepareDropTableJson(it);
      });
      const jsonRenameTables = renamedTables.map((it) => {
        return prepareRenameTableJson(it.from, it.to);
      });
      const jsonRenameColumnsStatements = columnRenames.map((it) => prepareRenameColumns(it.table, "", it.renames)).flat();
      const jsonDropColumnsStatemets = columnDeletes.map((it) => _prepareDropColumns(it.table, "", it.columns)).flat();
      const jsonAddColumnsStatemets = columnCreates.map((it) => {
        return _prepareSqliteAddColumns(
          it.table,
          it.columns,
          tablesMap[it.table] && tablesMap[it.table].addedForeignKeys ? Object.values(tablesMap[it.table].addedForeignKeys) : []
        );
      }).flat();
      const rColumns = jsonRenameColumnsStatements.map((it) => {
        const tableName = it.tableName;
        const schema5 = it.schema;
        return {
          from: { schema: schema5, table: tableName, column: it.oldColumnName },
          to: { schema: schema5, table: tableName, column: it.newColumnName }
        };
      });
      const rTables = renamedTables.map((it) => {
        return { from: it.from, to: it.to };
      });
      const _meta = prepareMigrationMeta([], rTables, rColumns);
      const allAltered = typedResult.alteredTablesWithColumns;
      const jsonAddedCompositePKs = [];
      const jsonDeletedCompositePKs = [];
      const jsonAlteredCompositePKs = [];
      const jsonAddedUniqueConstraints = [];
      const jsonDeletedUniqueConstraints = [];
      const jsonAlteredUniqueConstraints = [];
      const jsonDeletedCheckConstraints = [];
      const jsonCreatedCheckConstraints = [];
      allAltered.forEach((it) => {
        let addedColumns = [];
        for (const addedPkName of Object.keys(it.addedCompositePKs)) {
          const addedPkColumns = it.addedCompositePKs[addedPkName];
          addedColumns = SQLiteSquasher.unsquashPK(addedPkColumns);
        }
        let deletedColumns = [];
        for (const deletedPkName of Object.keys(it.deletedCompositePKs)) {
          const deletedPkColumns = it.deletedCompositePKs[deletedPkName];
          deletedColumns = SQLiteSquasher.unsquashPK(deletedPkColumns);
        }
        const doPerformDeleteAndCreate = JSON.stringify(addedColumns) !== JSON.stringify(deletedColumns);
        let addedCompositePKs = [];
        let deletedCompositePKs = [];
        let alteredCompositePKs = [];
        if (doPerformDeleteAndCreate) {
          addedCompositePKs = prepareAddCompositePrimaryKeySqlite(
            it.name,
            it.addedCompositePKs
          );
          deletedCompositePKs = prepareDeleteCompositePrimaryKeySqlite(
            it.name,
            it.deletedCompositePKs
          );
        }
        alteredCompositePKs = prepareAlterCompositePrimaryKeySqlite(
          it.name,
          it.alteredCompositePKs
        );
        let addedUniqueConstraints = [];
        let deletedUniqueConstraints = [];
        let alteredUniqueConstraints = [];
        let createdCheckConstraints = [];
        let deletedCheckConstraints = [];
        addedUniqueConstraints = prepareAddUniqueConstraintPg(
          it.name,
          it.schema,
          it.addedUniqueConstraints
        );
        deletedUniqueConstraints = prepareDeleteUniqueConstraintPg(
          it.name,
          it.schema,
          it.deletedUniqueConstraints
        );
        if (it.alteredUniqueConstraints) {
          const added = {};
          const deleted = {};
          for (const k of Object.keys(it.alteredUniqueConstraints)) {
            added[k] = it.alteredUniqueConstraints[k].__new;
            deleted[k] = it.alteredUniqueConstraints[k].__old;
          }
          addedUniqueConstraints.push(
            ...prepareAddUniqueConstraintPg(it.name, it.schema, added)
          );
          deletedUniqueConstraints.push(
            ...prepareDeleteUniqueConstraintPg(it.name, it.schema, deleted)
          );
        }
        createdCheckConstraints = prepareAddCheckConstraint(it.name, it.schema, it.addedCheckConstraints);
        deletedCheckConstraints = prepareDeleteCheckConstraint(
          it.name,
          it.schema,
          it.deletedCheckConstraints
        );
        if (it.alteredCheckConstraints && action !== "push") {
          const added = {};
          const deleted = {};
          for (const k of Object.keys(it.alteredCheckConstraints)) {
            added[k] = it.alteredCheckConstraints[k].__new;
            deleted[k] = it.alteredCheckConstraints[k].__old;
          }
          createdCheckConstraints.push(...prepareAddCheckConstraint(it.name, it.schema, added));
          deletedCheckConstraints.push(...prepareDeleteCheckConstraint(it.name, it.schema, deleted));
        }
        jsonAddedCompositePKs.push(...addedCompositePKs);
        jsonDeletedCompositePKs.push(...deletedCompositePKs);
        jsonAlteredCompositePKs.push(...alteredCompositePKs);
        jsonAddedUniqueConstraints.push(...addedUniqueConstraints);
        jsonDeletedUniqueConstraints.push(...deletedUniqueConstraints);
        jsonAlteredUniqueConstraints.push(...alteredUniqueConstraints);
        jsonCreatedCheckConstraints.push(...createdCheckConstraints);
        jsonDeletedCheckConstraints.push(...deletedCheckConstraints);
      });
      const jsonTableAlternations = allAltered.map((it) => {
        return prepareSqliteAlterColumns(it.name, it.schema, it.altered, json22);
      }).flat();
      const jsonCreateIndexesForAllAlteredTables = allAltered.map((it) => {
        return prepareCreateIndexesJson(
          it.name,
          it.schema,
          it.addedIndexes || {},
          curFull.internal
        );
      }).flat();
      const jsonDropIndexesForAllAlteredTables = allAltered.map((it) => {
        return prepareDropIndexesJson(
          it.name,
          it.schema,
          it.deletedIndexes || {}
        );
      }).flat();
      allAltered.forEach((it) => {
        const droppedIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__old;
            return current;
          },
          {}
        );
        const createdIndexes = Object.keys(it.alteredIndexes).reduce(
          (current, item) => {
            current[item] = it.alteredIndexes[item].__new;
            return current;
          },
          {}
        );
        jsonCreateIndexesForAllAlteredTables.push(
          ...prepareCreateIndexesJson(
            it.name,
            it.schema,
            createdIndexes || {},
            curFull.internal
          )
        );
        jsonDropIndexesForAllAlteredTables.push(
          ...prepareDropIndexesJson(it.name, it.schema, droppedIndexes || {})
        );
      });
      const jsonReferencesForAllAlteredTables = allAltered.map((it) => {
        const forAdded = prepareLibSQLCreateReferencesJson(
          it.name,
          it.schema,
          it.addedForeignKeys,
          json22,
          action
        );
        const forAltered = prepareLibSQLDropReferencesJson(
          it.name,
          it.schema,
          it.deletedForeignKeys,
          json22,
          _meta,
          action
        );
        const alteredFKs = prepareAlterReferencesJson(it.name, it.schema, it.alteredForeignKeys);
        return [...forAdded, ...forAltered, ...alteredFKs];
      }).flat();
      const jsonCreatedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t) => t.type === "create_reference"
      );
      const jsonDroppedReferencesForAlteredTables = jsonReferencesForAllAlteredTables.filter(
        (t) => t.type === "delete_reference"
      );
      const createViews = [];
      const dropViews = [];
      createViews.push(
        ...createdViews.filter((it) => !it.isExisting).map((it) => {
          return prepareSqliteCreateViewJson(
            it.name,
            it.definition
          );
        })
      );
      dropViews.push(
        ...deletedViews.filter((it) => !it.isExisting).map((it) => {
          return prepareDropViewJson(it.name);
        })
      );
      dropViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
          return prepareDropViewJson(it.from.name);
        })
      );
      createViews.push(
        ...renamedViews.filter((it) => !it.to.isExisting).map((it) => {
          return prepareSqliteCreateViewJson(it.to.name, it.to.definition);
        })
      );
      const alteredViews = typedResult.alteredViews.filter((it) => !json22.views[it.name].isExisting);
      for (const alteredView of alteredViews) {
        const { definition } = json22.views[alteredView.name];
        if (alteredView.alteredExisting || alteredView.alteredDefinition && action !== "push") {
          dropViews.push(prepareDropViewJson(alteredView.name));
          createViews.push(
            prepareSqliteCreateViewJson(
              alteredView.name,
              definition
            )
          );
        }
      }
      const jsonStatements = [];
      jsonStatements.push(...jsonCreateTables);
      jsonStatements.push(...jsonDropTables);
      jsonStatements.push(...jsonRenameTables);
      jsonStatements.push(...jsonRenameColumnsStatements);
      jsonStatements.push(...jsonDroppedReferencesForAlteredTables);
      jsonStatements.push(...jsonDeletedCheckConstraints);
      jsonStatements.push(...jsonDropIndexesForAllAlteredTables);
      jsonStatements.push(...jsonDeletedCompositePKs);
      jsonStatements.push(...jsonTableAlternations);
      jsonStatements.push(...jsonAddedCompositePKs);
      jsonStatements.push(...jsonAddColumnsStatemets);
      jsonStatements.push(...jsonCreateIndexesForCreatedTables);
      jsonStatements.push(...jsonCreateIndexesForAllAlteredTables);
      jsonStatements.push(...jsonCreatedCheckConstraints);
      jsonStatements.push(...dropViews);
      jsonStatements.push(...createViews);
      jsonStatements.push(...jsonCreatedReferencesForAlteredTables);
      jsonStatements.push(...jsonDropColumnsStatemets);
      jsonStatements.push(...jsonAlteredCompositePKs);
      jsonStatements.push(...jsonAlteredUniqueConstraints);
      const combinedJsonStatements = libSQLCombineStatements(jsonStatements, json22, action);
      const sqlStatements = fromJson(
        combinedJsonStatements,
        "turso",
        action,
        json22
      );
      const uniqueSqlStatements = [];
      sqlStatements.forEach((ss) => {
        if (!uniqueSqlStatements.includes(ss)) {
          uniqueSqlStatements.push(ss);
        }
      });
      return {
        statements: combinedJsonStatements,
        sqlStatements: uniqueSqlStatements,
        _meta
      };
    };
  }
});

// src/utils/words.ts
var init_words = __esm({
  "src/utils/words.ts"() {
    "use strict";
  }
});

// src/schemaValidator.ts
var dialects, dialect4, commonSquashedSchema, commonSchema;
var init_schemaValidator = __esm({
  "src/schemaValidator.ts"() {
    "use strict";
    init_esm();
    init_mysqlSchema();
    init_pgSchema();
    init_singlestoreSchema();
    init_sqliteSchema();
    dialects = ["postgresql", "mysql", "sqlite", "turso", "singlestore", "gel"];
    dialect4 = enumType(dialects);
    commonSquashedSchema = unionType([
      pgSchemaSquashed,
      mysqlSchemaSquashed,
      SQLiteSchemaSquashed,
      singlestoreSchemaSquashed
    ]);
    commonSchema = unionType([pgSchema, mysqlSchema, sqliteSchema, singlestoreSchema]);
  }
});

// src/cli/validations/common.ts
var sqliteDriversLiterals, postgresqlDriversLiterals, prefixes, prefix, casingTypes, casingType, sqliteDriver, postgresDriver, driver, configMigrations, configCommonSchema, casing, introspectParams, configIntrospectCliSchema, configGenerateSchema, configPushSchema;
var init_common = __esm({
  "src/cli/validations/common.ts"() {
    "use strict";
    init_esm();
    init_schemaValidator();
    init_outputs();
    sqliteDriversLiterals = [
      literalType("d1-http"),
      literalType("expo"),
      literalType("durable-sqlite")
    ];
    postgresqlDriversLiterals = [
      literalType("aws-data-api"),
      literalType("pglite")
    ];
    prefixes = [
      "index",
      "timestamp",
      "supabase",
      "unix",
      "none"
    ];
    prefix = enumType(prefixes);
    {
      const _2 = "";
    }
    casingTypes = ["snake_case", "camelCase"];
    casingType = enumType(casingTypes);
    sqliteDriver = unionType(sqliteDriversLiterals);
    postgresDriver = unionType(postgresqlDriversLiterals);
    driver = unionType([sqliteDriver, postgresDriver]);
    configMigrations = objectType({
      table: stringType().optional(),
      schema: stringType().optional(),
      prefix: prefix.optional().default("index")
    }).optional();
    configCommonSchema = objectType({
      dialect: dialect4,
      schema: unionType([stringType(), stringType().array()]).optional(),
      out: stringType().optional(),
      breakpoints: booleanType().optional().default(true),
      verbose: booleanType().optional().default(false),
      driver: driver.optional(),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
      migrations: configMigrations,
      dbCredentials: anyType().optional(),
      casing: casingType.optional(),
      sql: booleanType().default(true)
    }).passthrough();
    casing = unionType([literalType("camel"), literalType("preserve")]).default(
      "camel"
    );
    introspectParams = objectType({
      schema: unionType([stringType(), stringType().array()]).optional(),
      out: stringType().optional().default("./drizzle"),
      breakpoints: booleanType().default(true),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
      introspect: objectType({
        casing
      }).default({ casing: "camel" })
    });
    configIntrospectCliSchema = objectType({
      schema: unionType([stringType(), stringType().array()]).optional(),
      out: stringType().optional().default("./drizzle"),
      breakpoints: booleanType().default(true),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
      introspectCasing: unionType([literalType("camel"), literalType("preserve")]).default(
        "camel"
      )
    });
    configGenerateSchema = objectType({
      schema: unionType([stringType(), stringType().array()]),
      out: stringType().optional().default("./drizzle"),
      breakpoints: booleanType().default(true)
    });
    configPushSchema = objectType({
      dialect: dialect4,
      schema: unionType([stringType(), stringType().array()]),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).default(["public"]),
      verbose: booleanType().default(false),
      strict: booleanType().default(false),
      out: stringType().optional()
    });
  }
});

// src/cli/validations/outputs.ts
var withStyle;
var init_outputs = __esm({
  "src/cli/validations/outputs.ts"() {
    "use strict";
    init_source();
    init_common();
    withStyle = {
      error: (str) => `${source_default.red(`${source_default.white.bgRed(" Invalid input ")} ${str}`)}`,
      warning: (str) => `${source_default.white.bgGray(" Warning ")} ${str}`,
      errorWarning: (str) => `${source_default.red(`${source_default.white.bgRed(" Warning ")} ${str}`)}`,
      fullWarning: (str) => `${source_default.black.bgYellow(" Warning ")} ${source_default.bold(str)}`,
      suggestion: (str) => `${source_default.white.bgGray(" Suggestion ")} ${str}`,
      info: (str) => `${source_default.grey(str)}`
    };
  }
});

// src/cli/commands/migrate.ts
var import_hanji2, schemasResolver, tablesResolver, viewsResolver, mySqlViewsResolver, sqliteViewsResolver, sequencesResolver, roleResolver, policyResolver, indPolicyResolver, enumsResolver, columnsResolver, promptColumnsConflicts, promptNamedConflict, promptNamedWithSchemasConflict, promptSchemasConflict, BREAKPOINT;
var init_migrate = __esm({
  "src/cli/commands/migrate.ts"() {
    "use strict";
    init_migrationPreparator();
    init_source();
    import_hanji2 = __toESM(require_hanji());
    init_singlestoreSchema();
    init_mysqlSchema();
    init_pgSchema();
    init_sqliteSchema();
    init_snapshotsDiffer();
    init_utils();
    init_words();
    init_outputs();
    init_views();
    schemasResolver = async (input) => {
      try {
        const { created, deleted, renamed } = await promptSchemasConflict(
          input.created,
          input.deleted
        );
        return { created, deleted, renamed };
      } catch (e) {
        console.error(e);
        throw e;
      }
    };
    tablesResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "table"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e) {
        console.error(e);
        throw e;
      }
    };
    viewsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "view"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e) {
        console.error(e);
        throw e;
      }
    };
    mySqlViewsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "view"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e) {
        console.error(e);
        throw e;
      }
    };
    sqliteViewsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "view"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e) {
        console.error(e);
        throw e;
      }
    };
    sequencesResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "sequence"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e) {
        console.error(e);
        throw e;
      }
    };
    roleResolver = async (input) => {
      const result = await promptNamedConflict(
        input.created,
        input.deleted,
        "role"
      );
      return {
        created: result.created,
        deleted: result.deleted,
        renamed: result.renamed
      };
    };
    policyResolver = async (input) => {
      const result = await promptColumnsConflicts(
        input.tableName,
        input.created,
        input.deleted
      );
      return {
        tableName: input.tableName,
        schema: input.schema,
        created: result.created,
        deleted: result.deleted,
        renamed: result.renamed
      };
    };
    indPolicyResolver = async (input) => {
      const result = await promptNamedConflict(
        input.created,
        input.deleted,
        "policy"
      );
      return {
        created: result.created,
        deleted: result.deleted,
        renamed: result.renamed
      };
    };
    enumsResolver = async (input) => {
      try {
        const { created, deleted, moved, renamed } = await promptNamedWithSchemasConflict(
          input.created,
          input.deleted,
          "enum"
        );
        return {
          created,
          deleted,
          moved,
          renamed
        };
      } catch (e) {
        console.error(e);
        throw e;
      }
    };
    columnsResolver = async (input) => {
      const result = await promptColumnsConflicts(
        input.tableName,
        input.created,
        input.deleted
      );
      return {
        tableName: input.tableName,
        schema: input.schema,
        created: result.created,
        deleted: result.deleted,
        renamed: result.renamed
      };
    };
    promptColumnsConflicts = async (tableName, newColumns, missingColumns) => {
      if (newColumns.length === 0 || missingColumns.length === 0) {
        return { created: newColumns, renamed: [], deleted: missingColumns };
      }
      const result = {
        created: [],
        renamed: [],
        deleted: []
      };
      let index6 = 0;
      let leftMissing = [...missingColumns];
      do {
        const created = newColumns[index6];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji2.render)(
          new ResolveColumnSelect(tableName, created, promptData)
        );
        if (status === "aborted") {
          console.error("ERROR");
          process.exit(1);
        }
        if (isRenamePromptItem(data)) {
          console.log(
            `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
              "column will be renamed"
            )}`
          );
          result.renamed.push(data);
          delete leftMissing[leftMissing.indexOf(data.from)];
          leftMissing = leftMissing.filter(Boolean);
        } else {
          console.log(
            `${source_default.green("+")} ${data.name} ${source_default.gray(
              "column will be created"
            )}`
          );
          result.created.push(created);
        }
        index6 += 1;
      } while (index6 < newColumns.length);
      console.log(
        source_default.gray(`--- all columns conflicts in ${tableName} table resolved ---
`)
      );
      result.deleted.push(...leftMissing);
      return result;
    };
    promptNamedConflict = async (newItems, missingItems, entity) => {
      if (missingItems.length === 0 || newItems.length === 0) {
        return {
          created: newItems,
          renamed: [],
          deleted: missingItems
        };
      }
      const result = { created: [], renamed: [], deleted: [] };
      let index6 = 0;
      let leftMissing = [...missingItems];
      do {
        const created = newItems[index6];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji2.render)(
          new ResolveSelectNamed(created, promptData, entity)
        );
        if (status === "aborted") {
          console.error("ERROR");
          process.exit(1);
        }
        if (isRenamePromptItem(data)) {
          console.log(
            `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
              `${entity} will be renamed/moved`
            )}`
          );
          if (data.from.name !== data.to.name) {
            result.renamed.push(data);
          }
          delete leftMissing[leftMissing.indexOf(data.from)];
          leftMissing = leftMissing.filter(Boolean);
        } else {
          console.log(
            `${source_default.green("+")} ${data.name} ${source_default.gray(
              `${entity} will be created`
            )}`
          );
          result.created.push(created);
        }
        index6 += 1;
      } while (index6 < newItems.length);
      console.log(source_default.gray(`--- all ${entity} conflicts resolved ---
`));
      result.deleted.push(...leftMissing);
      return result;
    };
    promptNamedWithSchemasConflict = async (newItems, missingItems, entity) => {
      if (missingItems.length === 0 || newItems.length === 0) {
        return {
          created: newItems,
          renamed: [],
          moved: [],
          deleted: missingItems
        };
      }
      const result = { created: [], renamed: [], moved: [], deleted: [] };
      let index6 = 0;
      let leftMissing = [...missingItems];
      do {
        const created = newItems[index6];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji2.render)(
          new ResolveSelect(created, promptData, entity)
        );
        if (status === "aborted") {
          console.error("ERROR");
          process.exit(1);
        }
        if (isRenamePromptItem(data)) {
          const schemaFromPrefix = !data.from.schema || data.from.schema === "public" ? "" : `${data.from.schema}.`;
          const schemaToPrefix = !data.to.schema || data.to.schema === "public" ? "" : `${data.to.schema}.`;
          console.log(
            `${source_default.yellow("~")} ${schemaFromPrefix}${data.from.name} \u203A ${schemaToPrefix}${data.to.name} ${source_default.gray(
              `${entity} will be renamed/moved`
            )}`
          );
          if (data.from.name !== data.to.name) {
            result.renamed.push(data);
          }
          if (data.from.schema !== data.to.schema) {
            result.moved.push({
              name: data.from.name,
              schemaFrom: data.from.schema || "public",
              schemaTo: data.to.schema || "public"
            });
          }
          delete leftMissing[leftMissing.indexOf(data.from)];
          leftMissing = leftMissing.filter(Boolean);
        } else {
          console.log(
            `${source_default.green("+")} ${data.name} ${source_default.gray(
              `${entity} will be created`
            )}`
          );
          result.created.push(created);
        }
        index6 += 1;
      } while (index6 < newItems.length);
      console.log(source_default.gray(`--- all ${entity} conflicts resolved ---
`));
      result.deleted.push(...leftMissing);
      return result;
    };
    promptSchemasConflict = async (newSchemas, missingSchemas) => {
      if (missingSchemas.length === 0 || newSchemas.length === 0) {
        return { created: newSchemas, renamed: [], deleted: missingSchemas };
      }
      const result = {
        created: [],
        renamed: [],
        deleted: []
      };
      let index6 = 0;
      let leftMissing = [...missingSchemas];
      do {
        const created = newSchemas[index6];
        const renames = leftMissing.map((it) => {
          return { from: it, to: created };
        });
        const promptData = [created, ...renames];
        const { status, data } = await (0, import_hanji2.render)(
          new ResolveSchemasSelect(created, promptData)
        );
        if (status === "aborted") {
          console.error("ERROR");
          process.exit(1);
        }
        if (isRenamePromptItem(data)) {
          console.log(
            `${source_default.yellow("~")} ${data.from.name} \u203A ${data.to.name} ${source_default.gray(
              "schema will be renamed"
            )}`
          );
          result.renamed.push(data);
          delete leftMissing[leftMissing.indexOf(data.from)];
          leftMissing = leftMissing.filter(Boolean);
        } else {
          console.log(
            `${source_default.green("+")} ${data.name} ${source_default.gray(
              "schema will be created"
            )}`
          );
          result.created.push(created);
        }
        index6 += 1;
      } while (index6 < newSchemas.length);
      console.log(source_default.gray("--- all schemas conflicts resolved ---\n"));
      result.deleted.push(...leftMissing);
      return result;
    };
    BREAKPOINT = "--> statement-breakpoint\n";
  }
});

// ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/brace-expressions.js
var posixClasses, braceEscape, regexpEscape, rangesToString, parseClass;
var init_brace_expressions = __esm({
  "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/brace-expressions.js"() {
    "use strict";
    posixClasses = {
      "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true],
      "[:alpha:]": ["\\p{L}\\p{Nl}", true],
      "[:ascii:]": ["\\x00-\\x7f", false],
      "[:blank:]": ["\\p{Zs}\\t", true],
      "[:cntrl:]": ["\\p{Cc}", true],
      "[:digit:]": ["\\p{Nd}", true],
      "[:graph:]": ["\\p{Z}\\p{C}", true, true],
      "[:lower:]": ["\\p{Ll}", true],
      "[:print:]": ["\\p{C}", true],
      "[:punct:]": ["\\p{P}", true],
      "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true],
      "[:upper:]": ["\\p{Lu}", true],
      "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true],
      "[:xdigit:]": ["A-Fa-f0-9", false]
    };
    braceEscape = (s) => s.replace(/[[\]\\-]/g, "\\$&");
    regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    rangesToString = (ranges) => ranges.join("");
    parseClass = (glob2, position) => {
      const pos = position;
      if (glob2.charAt(pos) !== "[") {
        throw new Error("not in a brace expression");
      }
      const ranges = [];
      const negs = [];
      let i = pos + 1;
      let sawStart = false;
      let uflag = false;
      let escaping = false;
      let negate = false;
      let endPos = pos;
      let rangeStart = "";
      WHILE: while (i < glob2.length) {
        const c = glob2.charAt(i);
        if ((c === "!" || c === "^") && i === pos + 1) {
          negate = true;
          i++;
          continue;
        }
        if (c === "]" && sawStart && !escaping) {
          endPos = i + 1;
          break;
        }
        sawStart = true;
        if (c === "\\") {
          if (!escaping) {
            escaping = true;
            i++;
            continue;
          }
        }
        if (c === "[" && !escaping) {
          for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
            if (glob2.startsWith(cls, i)) {
              if (rangeStart) {
                return ["$.", false, glob2.length - pos, true];
              }
              i += cls.length;
              if (neg)
                negs.push(unip);
              else
                ranges.push(unip);
              uflag = uflag || u;
              continue WHILE;
            }
          }
        }
        escaping = false;
        if (rangeStart) {
          if (c > rangeStart) {
            ranges.push(braceEscape(rangeStart) + "-" + braceEscape(c));
          } else if (c === rangeStart) {
            ranges.push(braceEscape(c));
          }
          rangeStart = "";
          i++;
          continue;
        }
        if (glob2.startsWith("-]", i + 1)) {
          ranges.push(braceEscape(c + "-"));
          i += 2;
          continue;
        }
        if (glob2.startsWith("-", i + 1)) {
          rangeStart = c;
          i += 2;
          continue;
        }
        ranges.push(braceEscape(c));
        i++;
      }
      if (endPos < i) {
        return ["", false, 0, false];
      }
      if (!ranges.length && !negs.length) {
        return ["$.", false, glob2.length - pos, true];
      }
      if (negs.length === 0 && ranges.length === 1 && /^\\?.$/.test(ranges[0]) && !negate) {
        const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
        return [regexpEscape(r), false, endPos - pos, false];
      }
      const sranges = "[" + (negate ? "^" : "") + rangesToString(ranges) + "]";
      const snegs = "[" + (negate ? "" : "^") + rangesToString(negs) + "]";
      const comb = ranges.length && negs.length ? "(" + sranges + "|" + snegs + ")" : ranges.length ? sranges : snegs;
      return [comb, uflag, endPos - pos, true];
    };
  }
});

// ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/escape.js
var escape;
var init_escape = __esm({
  "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/escape.js"() {
    "use strict";
    escape = (s, { windowsPathsNoEscape = false } = {}) => {
      return windowsPathsNoEscape ? s.replace(/[?*()[\]]/g, "[$&]") : s.replace(/[?*()[\]\\]/g, "\\$&");
    };
  }
});

// ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/unescape.js
var unescape;
var init_unescape = __esm({
  "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/unescape.js"() {
    "use strict";
    unescape = (s, { windowsPathsNoEscape = false } = {}) => {
      return windowsPathsNoEscape ? s.replace(/\[([^\/\\])\]/g, "$1") : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1");
    };
  }
});

// ../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/index.js
var import_brace_expansion, minimatch, starDotExtRE, starDotExtTest, starDotExtTestDot, starDotExtTestNocase, starDotExtTestNocaseDot, starDotStarRE, starDotStarTest, starDotStarTestDot, dotStarRE, dotStarTest, starRE, starTest, starTestDot, qmarksRE, qmarksTestNocase, qmarksTestNocaseDot, qmarksTestDot, qmarksTest, qmarksTestNoExt, qmarksTestNoExtDot, defaultPlatform, path, sep, GLOBSTAR, plTypes, qmark, star, twoStarDot, twoStarNoDot, charSet, reSpecials, addPatternStartSet, filter, ext, defaults, braceExpand, MAX_PATTERN_LENGTH, assertValidPattern, makeRe, match, globUnescape, globMagic, regExpEscape, Minimatch;
var init_mjs = __esm({
  "../node_modules/.pnpm/minimatch@7.4.6/node_modules/minimatch/dist/mjs/index.js"() {
    "use strict";
    import_brace_expansion = __toESM(require_brace_expansion(), 1);
    init_brace_expressions();
    init_escape();
    init_unescape();
    init_escape();
    init_unescape();
    minimatch = (p, pattern, options = {}) => {
      assertValidPattern(pattern);
      if (!options.nocomment && pattern.charAt(0) === "#") {
        return false;
      }
      return new Minimatch(pattern, options).match(p);
    };
    starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
    starDotExtTest = (ext2) => (f) => !f.startsWith(".") && f.endsWith(ext2);
    starDotExtTestDot = (ext2) => (f) => f.endsWith(ext2);
    starDotExtTestNocase = (ext2) => {
      ext2 = ext2.toLowerCase();
      return (f) => !f.startsWith(".") && f.toLowerCase().endsWith(ext2);
    };
    starDotExtTestNocaseDot = (ext2) => {
      ext2 = ext2.toLowerCase();
      return (f) => f.toLowerCase().endsWith(ext2);
    };
    starDotStarRE = /^\*+\.\*+$/;
    starDotStarTest = (f) => !f.startsWith(".") && f.includes(".");
    starDotStarTestDot = (f) => f !== "." && f !== ".." && f.includes(".");
    dotStarRE = /^\.\*+$/;
    dotStarTest = (f) => f !== "." && f !== ".." && f.startsWith(".");
    starRE = /^\*+$/;
    starTest = (f) => f.length !== 0 && !f.startsWith(".");
    starTestDot = (f) => f.length !== 0 && f !== "." && f !== "..";
    qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
    qmarksTestNocase = ([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExt([$0]);
      if (!ext2)
        return noext;
      ext2 = ext2.toLowerCase();
      return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
    };
    qmarksTestNocaseDot = ([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExtDot([$0]);
      if (!ext2)
        return noext;
      ext2 = ext2.toLowerCase();
      return (f) => noext(f) && f.toLowerCase().endsWith(ext2);
    };
    qmarksTestDot = ([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExtDot([$0]);
      return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
    };
    qmarksTest = ([$0, ext2 = ""]) => {
      const noext = qmarksTestNoExt([$0]);
      return !ext2 ? noext : (f) => noext(f) && f.endsWith(ext2);
    };
    qmarksTestNoExt = ([$0]) => {
      const len = $0.length;
      return (f) => f.length === len && !f.startsWith(".");
    };
    qmarksTestNoExtDot = ([$0]) => {
      const len = $0.length;
      return (f) => f.length === len && f !== "." && f !== "..";
    };
    defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
    path = {
      win32: { sep: "\\" },
      posix: { sep: "/" }
    };
    sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;
    minimatch.sep = sep;
    GLOBSTAR = Symbol("globstar **");
    minimatch.GLOBSTAR = GLOBSTAR;
    plTypes = {
      "!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
      "?": { open: "(?:", close: ")?" },
      "+": { open: "(?:", close: ")+" },
      "*": { open: "(?:", close: ")*" },
      "@": { open: "(?:", close: ")" }
    };
    qmark = "[^/]";
    star = qmark + "*?";
    twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
    twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
    charSet = (s) => s.split("").reduce((set, c) => {
      set[c] = true;
      return set;
    }, {});
    reSpecials = charSet("().*{}+?[]^$\\!");
    addPatternStartSet = charSet("[.(");
    filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
    minimatch.filter = filter;
    ext = (a, b = {}) => Object.assign({}, a, b);
    defaults = (def) => {
      if (!def || typeof def !== "object" || !Object.keys(def).length) {
        return minimatch;
      }
      const orig = minimatch;
      const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
      return Object.assign(m, {
        Minimatch: class Minimatch extends orig.Minimatch {
          constructor(pattern, options = {}) {
            super(pattern, ext(def, options));
          }
          static defaults(options) {
            return orig.defaults(ext(def, options)).Minimatch;
          }
        },
        unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
        escape: (s, options = {}) => orig.escape(s, ext(def, options)),
        filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
        defaults: (options) => orig.defaults(ext(def, options)),
        makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
        braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
        match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
        sep: orig.sep,
        GLOBSTAR
      });
    };
    minimatch.defaults = defaults;
    braceExpand = (pattern, options = {}) => {
      assertValidPattern(pattern);
      if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
        return [pattern];
      }
      return (0, import_brace_expansion.default)(pattern);
    };
    minimatch.braceExpand = braceExpand;
    MAX_PATTERN_LENGTH = 1024 * 64;
    assertValidPattern = (pattern) => {
      if (typeof pattern !== "string") {
        throw new TypeError("invalid pattern");
      }
      if (pattern.length > MAX_PATTERN_LENGTH) {
        throw new TypeError("pattern is too long");
      }
    };
    makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
    minimatch.makeRe = makeRe;
    match = (list, pattern, options = {}) => {
      const mm = new Minimatch(pattern, options);
      list = list.filter((f) => mm.match(f));
      if (mm.options.nonull && !list.length) {
        list.push(pattern);
      }
      return list;
    };
    minimatch.match = match;
    globUnescape = (s) => s.replace(/\\(.)/g, "$1");
    globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
    regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    Minimatch = class {
      constructor(pattern, options = {}) {
        __publicField(this, "options");
        __publicField(this, "set");
        __publicField(this, "pattern");
        __publicField(this, "windowsPathsNoEscape");
        __publicField(this, "nonegate");
        __publicField(this, "negate");
        __publicField(this, "comment");
        __publicField(this, "empty");
        __publicField(this, "preserveMultipleSlashes");
        __publicField(this, "partial");
        __publicField(this, "globSet");
        __publicField(this, "globParts");
        __publicField(this, "nocase");
        __publicField(this, "isWindows");
        __publicField(this, "platform");
        __publicField(this, "windowsNoMagicRoot");
        __publicField(this, "regexp");
        assertValidPattern(pattern);
        options = options || {};
        this.options = options;
        this.pattern = pattern;
        this.platform = options.platform || defaultPlatform;
        this.isWindows = this.platform === "win32";
        this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
        if (this.windowsPathsNoEscape) {
          this.pattern = this.pattern.replace(/\\/g, "/");
        }
        this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
        this.regexp = null;
        this.negate = false;
        this.nonegate = !!options.nonegate;
        this.comment = false;
        this.empty = false;
        this.partial = !!options.partial;
        this.nocase = !!this.options.nocase;
        this.windowsNoMagicRoot = options.windowsNoMagicRoot !== void 0 ? options.windowsNoMagicRoot : !!(this.isWindows && this.nocase);
        this.globSet = [];
        this.globParts = [];
        this.set = [];
        this.make();
      }
      hasMagic() {
        if (this.options.magicalBraces && this.set.length > 1) {
          return true;
        }
        for (const pattern of this.set) {
          for (const part of pattern) {
            if (typeof part !== "string")
              return true;
          }
        }
        return false;
      }
      debug(..._2) {
      }
      make() {
        const pattern = this.pattern;
        const options = this.options;
        if (!options.nocomment && pattern.charAt(0) === "#") {
          this.comment = true;
          return;
        }
        if (!pattern) {
          this.empty = true;
          return;
        }
        this.parseNegate();
        this.globSet = [...new Set(this.braceExpand())];
        if (options.debug) {
          this.debug = (...args) => console.error(...args);
        }
        this.debug(this.pattern, this.globSet);
        const rawGlobParts = this.globSet.map((s) => this.slashSplit(s));
        this.globParts = this.preprocess(rawGlobParts);
        this.debug(this.pattern, this.globParts);
        let set = this.globParts.map((s, _2, __) => {
          if (this.isWindows && this.windowsNoMagicRoot) {
            const isUNC = s[0] === "" && s[1] === "" && (s[2] === "?" || !globMagic.test(s[2])) && !globMagic.test(s[3]);
            const isDrive = /^[a-z]:/i.test(s[0]);
            if (isUNC) {
              return [...s.slice(0, 4), ...s.slice(4).map((ss) => this.parse(ss))];
            } else if (isDrive) {
              return [s[0], ...s.slice(1).map((ss) => this.parse(ss))];
            }
          }
          return s.map((ss) => this.parse(ss));
        });
        this.debug(this.pattern, set);
        this.set = set.filter((s) => s.indexOf(false) === -1);
        if (this.isWindows) {
          for (let i = 0; i < this.set.length; i++) {
            const p = this.set[i];
            if (p[0] === "" && p[1] === "" && this.globParts[i][2] === "?" && typeof p[3] === "string" && /^[a-z]:$/i.test(p[3])) {
              p[2] = "?";
            }
          }
        }
        this.debug(this.pattern, this.set);
      }
      // various transforms to equivalent pattern sets that are
      // faster to process in a filesystem walk.  The goal is to
      // eliminate what we can, and push all ** patterns as far
      // to the right as possible, even if it increases the number
      // of patterns that we have to process.
      preprocess(globParts) {
        if (this.options.noglobstar) {
          for (let i = 0; i < globParts.length; i++) {
            for (let j = 0; j < globParts[i].length; j++) {
              if (globParts[i][j] === "**") {
                globParts[i][j] = "*";
              }
            }
          }
        }
        const { optimizationLevel = 1 } = this.options;
        if (optimizationLevel >= 2) {
          globParts = this.firstPhasePreProcess(globParts);
          globParts = this.secondPhasePreProcess(globParts);
        } else if (optimizationLevel >= 1) {
          globParts = this.levelOneOptimize(globParts);
        } else {
          globParts = this.adjascentGlobstarOptimize(globParts);
        }
        return globParts;
      }
      // just get rid of adjascent ** portions
      adjascentGlobstarOptimize(globParts) {
        return globParts.map((parts) => {
          let gs = -1;
          while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
            let i = gs;
            while (parts[i + 1] === "**") {
              i++;
            }
            if (i !== gs) {
              parts.splice(gs, i - gs);
            }
          }
          return parts;
        });
      }
      // get rid of adjascent ** and resolve .. portions
      levelOneOptimize(globParts) {
        return globParts.map((parts) => {
          parts = parts.reduce((set, part) => {
            const prev = set[set.length - 1];
            if (part === "**" && prev === "**") {
              return set;
            }
            if (part === "..") {
              if (prev && prev !== ".." && prev !== "." && prev !== "**") {
                set.pop();
                return set;
              }
            }
            set.push(part);
            return set;
          }, []);
          return parts.length === 0 ? [""] : parts;
        });
      }
      levelTwoFileOptimize(parts) {
        if (!Array.isArray(parts)) {
          parts = this.slashSplit(parts);
        }
        let didSomething = false;
        do {
          didSomething = false;
          if (!this.preserveMultipleSlashes) {
            for (let i = 1; i < parts.length - 1; i++) {
              const p = parts[i];
              if (i === 1 && p === "" && parts[0] === "")
                continue;
              if (p === "." || p === "") {
                didSomething = true;
                parts.splice(i, 1);
                i--;
              }
            }
            if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
              didSomething = true;
              parts.pop();
            }
          }
          let dd = 0;
          while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
            const p = parts[dd - 1];
            if (p && p !== "." && p !== ".." && p !== "**") {
              didSomething = true;
              parts.splice(dd - 1, 2);
              dd -= 2;
            }
          }
        } while (didSomething);
        return parts.length === 0 ? [""] : parts;
      }
      // First phase: single-pattern processing
      // <pre> is 1 or more portions
      // <rest> is 1 or more portions
      // <p> is any portion other than ., .., '', or **
      // <e> is . or ''
      //
      // **/.. is *brutal* for filesystem walking performance, because
      // it effectively resets the recursive walk each time it occurs,
      // and ** cannot be reduced out by a .. pattern part like a regexp
      // or most strings (other than .., ., and '') can be.
      //
      // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
      // <pre>/<e>/<rest> -> <pre>/<rest>
      // <pre>/<p>/../<rest> -> <pre>/<rest>
      // **/**/<rest> -> **/<rest>
      //
      // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
      // this WOULD be allowed if ** did follow symlinks, or * didn't
      firstPhasePreProcess(globParts) {
        let didSomething = false;
        do {
          didSomething = false;
          for (let parts of globParts) {
            let gs = -1;
            while (-1 !== (gs = parts.indexOf("**", gs + 1))) {
              let gss = gs;
              while (parts[gss + 1] === "**") {
                gss++;
              }
              if (gss > gs) {
                parts.splice(gs + 1, gss - gs);
              }
              let next = parts[gs + 1];
              const p = parts[gs + 2];
              const p2 = parts[gs + 3];
              if (next !== "..")
                continue;
              if (!p || p === "." || p === ".." || !p2 || p2 === "." || p2 === "..") {
                continue;
              }
              didSomething = true;
              parts.splice(gs, 1);
              const other = parts.slice(0);
              other[gs] = "**";
              globParts.push(other);
              gs--;
            }
            if (!this.preserveMultipleSlashes) {
              for (let i = 1; i < parts.length - 1; i++) {
                const p = parts[i];
                if (i === 1 && p === "" && parts[0] === "")
                  continue;
                if (p === "." || p === "") {
                  didSomething = true;
                  parts.splice(i, 1);
                  i--;
                }
              }
              if (parts[0] === "." && parts.length === 2 && (parts[1] === "." || parts[1] === "")) {
                didSomething = true;
                parts.pop();
              }
            }
            let dd = 0;
            while (-1 !== (dd = parts.indexOf("..", dd + 1))) {
              const p = parts[dd - 1];
              if (p && p !== "." && p !== ".." && p !== "**") {
                didSomething = true;
                const needDot = dd === 1 && parts[dd + 1] === "**";
                const splin = needDot ? ["."] : [];
                parts.splice(dd - 1, 2, ...splin);
                if (parts.length === 0)
                  parts.push("");
                dd -= 2;
              }
            }
          }
        } while (didSomething);
        return globParts;
      }
      // second phase: multi-pattern dedupes
      // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
      // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
      // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
      //
      // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
      // ^-- not valid because ** doens't follow symlinks
      secondPhasePreProcess(globParts) {
        for (let i = 0; i < globParts.length - 1; i++) {
          for (let j = i + 1; j < globParts.length; j++) {
            const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
            if (!matched)
              continue;
            globParts[i] = matched;
            globParts[j] = [];
          }
        }
        return globParts.filter((gs) => gs.length);
      }
      partsMatch(a, b, emptyGSMatch = false) {
        let ai = 0;
        let bi = 0;
        let result = [];
        let which = "";
        while (ai < a.length && bi < b.length) {
          if (a[ai] === b[bi]) {
            result.push(which === "b" ? b[bi] : a[ai]);
            ai++;
            bi++;
          } else if (emptyGSMatch && a[ai] === "**" && b[bi] === a[ai + 1]) {
            result.push(a[ai]);
            ai++;
          } else if (emptyGSMatch && b[bi] === "**" && a[ai] === b[bi + 1]) {
            result.push(b[bi]);
            bi++;
          } else if (a[ai] === "*" && b[bi] && (this.options.dot || !b[bi].startsWith(".")) && b[bi] !== "**") {
            if (which === "b")
              return false;
            which = "a";
            result.push(a[ai]);
            ai++;
            bi++;
          } else if (b[bi] === "*" && a[ai] && (this.options.dot || !a[ai].startsWith(".")) && a[ai] !== "**") {
            if (which === "a")
              return false;
            which = "b";
            result.push(b[bi]);
            ai++;
            bi++;
          } else {
            return false;
          }
        }
        return a.length === b.length && result;
      }
      parseNegate() {
        if (this.nonegate)
          return;
        const pattern = this.pattern;
        let negate = false;
        let negateOffset = 0;
        for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {
          negate = !negate;
          negateOffset++;
        }
        if (negateOffset)
          this.pattern = pattern.slice(negateOffset);
        this.negate = negate;
      }
      // set partial to true to test if, for example,
      // "/a/b" matches the start of "/*/b/*/d"
      // Partial means, if you run out of file before you run
      // out of pattern, then that's fine, as long as all
      // the parts match.
      matchOne(file, pattern, partial = false) {
        const options = this.options;
        if (this.isWindows) {
          const fileUNC = file[0] === "" && file[1] === "" && file[2] === "?" && typeof file[3] === "string" && /^[a-z]:$/i.test(file[3]);
          const patternUNC = pattern[0] === "" && pattern[1] === "" && pattern[2] === "?" && typeof pattern[3] === "string" && /^[a-z]:$/i.test(pattern[3]);
          if (fileUNC && patternUNC) {
            const fd = file[3];
            const pd = pattern[3];
            if (fd.toLowerCase() === pd.toLowerCase()) {
              file[3] = pd;
            }
          } else if (patternUNC && typeof file[0] === "string") {
            const pd = pattern[3];
            const fd = file[0];
            if (pd.toLowerCase() === fd.toLowerCase()) {
              pattern[3] = fd;
              pattern = pattern.slice(3);
            }
          } else if (fileUNC && typeof pattern[0] === "string") {
            const fd = file[3];
            if (fd.toLowerCase() === pattern[0].toLowerCase()) {
              pattern[0] = fd;
              file = file.slice(3);
            }
          }
        }
        const { optimizationLevel = 1 } = this.options;
        if (optimizationLevel >= 2) {
          file = this.levelTwoFileOptimize(file);
        }
        this.debug("matchOne", this, { file, pattern });
        this.debug("matchOne", file.length, pattern.length);
        for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
          this.debug("matchOne loop");
          var p = pattern[pi];
          var f = file[fi];
          this.debug(pattern, p, f);
          if (p === false) {
            return false;
          }
          if (p === GLOBSTAR) {
            this.debug("GLOBSTAR", [pattern, p, f]);
            var fr = fi;
            var pr = pi + 1;
            if (pr === pl) {
              this.debug("** at the end");
              for (; fi < fl; fi++) {
                if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".")
                  return false;
              }
              return true;
            }
            while (fr < fl) {
              var swallowee = file[fr];
              this.debug("\nglobstar while", file, fr, pattern, pr, swallowee);
              if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
                this.debug("globstar found match!", fr, fl, swallowee);
                return true;
              } else {
                if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
                  this.debug("dot detected!", file, fr, pattern, pr);
                  break;
                }
                this.debug("globstar swallow a segment, and continue");
                fr++;
              }
            }
            if (partial) {
              this.debug("\n>>> no match, partial?", file, fr, pattern, pr);
              if (fr === fl) {
                return true;
              }
            }
            return false;
          }
          let hit;
          if (typeof p === "string") {
            hit = f === p;
            this.debug("string match", p, f, hit);
          } else {
            hit = p.test(f);
            this.debug("pattern match", p, f, hit);
          }
          if (!hit)
            return false;
        }
        if (fi === fl && pi === pl) {
          return true;
        } else if (fi === fl) {
          return partial;
        } else if (pi === pl) {
          return fi === fl - 1 && file[fi] === "";
        } else {
          throw new Error("wtf?");
        }
      }
      braceExpand() {
        return braceExpand(this.pattern, this.options);
      }
      parse(pattern) {
        assertValidPattern(pattern);
        const options = this.options;
        if (pattern === "**")
          return GLOBSTAR;
        if (pattern === "")
          return "";
        let m;
        let fastTest = null;
        if (m = pattern.match(starRE)) {
          fastTest = options.dot ? starTestDot : starTest;
        } else if (m = pattern.match(starDotExtRE)) {
          fastTest = (options.nocase ? options.dot ? starDotExtTestNocaseDot : starDotExtTestNocase : options.dot ? starDotExtTestDot : starDotExtTest)(m[1]);
        } else if (m = pattern.match(qmarksRE)) {
          fastTest = (options.nocase ? options.dot ? qmarksTestNocaseDot : qmarksTestNocase : options.dot ? qmarksTestDot : qmarksTest)(m);
        } else if (m = pattern.match(starDotStarRE)) {
          fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
        } else if (m = pattern.match(dotStarRE)) {
          fastTest = dotStarTest;
        }
        let re = "";
        let hasMagic = false;
        let escaping = false;
        const patternListStack = [];
        const negativeLists = [];
        let stateChar = false;
        let uflag = false;
        let pl;
        let dotTravAllowed = pattern.charAt(0) === ".";
        let dotFileAllowed = options.dot || dotTravAllowed;
        const patternStart = () => dotTravAllowed ? "" : dotFileAllowed ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
        const subPatternStart = (p) => p.charAt(0) === "." ? "" : options.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
        const clearStateChar = () => {
          if (stateChar) {
            switch (stateChar) {
              case "*":
                re += star;
                hasMagic = true;
                break;
              case "?":
                re += qmark;
                hasMagic = true;
                break;
              default:
                re += "\\" + stateChar;
                break;
            }
            this.debug("clearStateChar %j %j", stateChar, re);
            stateChar = false;
          }
        };
        for (let i = 0, c; i < pattern.length && (c = pattern.charAt(i)); i++) {
          this.debug("%s	%s %s %j", pattern, i, re, c);
          if (escaping) {
            if (c === "/") {
              return false;
            }
            if (reSpecials[c]) {
              re += "\\";
            }
            re += c;
            escaping = false;
            continue;
          }
          switch (c) {
            // Should already be path-split by now.
            /* c8 ignore start */
            case "/": {
              return false;
            }
            /* c8 ignore stop */
            case "\\":
              clearStateChar();
              escaping = true;
              continue;
            // the various stateChar values
            // for the "extglob" stuff.
            case "?":
            case "*":
            case "+":
            case "@":
            case "!":
              this.debug("%s	%s %s %j <-- stateChar", pattern, i, re, c);
              this.debug("call clearStateChar %j", stateChar);
              clearStateChar();
              stateChar = c;
              if (options.noext)
                clearStateChar();
              continue;
            case "(": {
              if (!stateChar) {
                re += "\\(";
                continue;
              }
              const plEntry = {
                type: stateChar,
                start: i - 1,
                reStart: re.length,
                open: plTypes[stateChar].open,
                close: plTypes[stateChar].close
              };
              this.debug(this.pattern, "	", plEntry);
              patternListStack.push(plEntry);
              re += plEntry.open;
              if (plEntry.start === 0 && plEntry.type !== "!") {
                dotTravAllowed = true;
                re += subPatternStart(pattern.slice(i + 1));
              }
              this.debug("plType %j %j", stateChar, re);
              stateChar = false;
              continue;
            }
            case ")": {
              const plEntry = patternListStack[patternListStack.length - 1];
              if (!plEntry) {
                re += "\\)";
                continue;
              }
              patternListStack.pop();
              clearStateChar();
              hasMagic = true;
              pl = plEntry;
              re += pl.close;
              if (pl.type === "!") {
                negativeLists.push(Object.assign(pl, { reEnd: re.length }));
              }
              continue;
            }
            case "|": {
              const plEntry = patternListStack[patternListStack.length - 1];
              if (!plEntry) {
                re += "\\|";
                continue;
              }
              clearStateChar();
              re += "|";
              if (plEntry.start === 0 && plEntry.type !== "!") {
                dotTravAllowed = true;
                re += subPatternStart(pattern.slice(i + 1));
              }
              continue;
            }
            // these are mostly the same in regexp and glob
            case "[":
              clearStateChar();
              const [src, needUflag, consumed, magic] = parseClass(pattern, i);
              if (consumed) {
                re += src;
                uflag = uflag || needUflag;
                i += consumed - 1;
                hasMagic = hasMagic || magic;
              } else {
                re += "\\[";
              }
              continue;
            case "]":
              re += "\\" + c;
              continue;
            default:
              clearStateChar();
              re += regExpEscape(c);
              break;
          }
        }
        for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
          let tail;
          tail = re.slice(pl.reStart + pl.open.length);
          this.debug(this.pattern, "setting tail", re, pl);
          tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_2, $1, $2) => {
            if (!$2) {
              $2 = "\\";
            }
            return $1 + $1 + $2 + "|";
          });
          this.debug("tail=%j\n   %s", tail, tail, pl, re);
          const t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
          hasMagic = true;
          re = re.slice(0, pl.reStart) + t + "\\(" + tail;
        }
        clearStateChar();
        if (escaping) {
          re += "\\\\";
        }
        const addPatternStart = addPatternStartSet[re.charAt(0)];
        for (let n = negativeLists.length - 1; n > -1; n--) {
          const nl = negativeLists[n];
          const nlBefore = re.slice(0, nl.reStart);
          const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
          let nlAfter = re.slice(nl.reEnd);
          const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
          const closeParensBefore = nlBefore.split(")").length;
          const openParensBefore = nlBefore.split("(").length - closeParensBefore;
          let cleanAfter = nlAfter;
          for (let i = 0; i < openParensBefore; i++) {
            cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
          }
          nlAfter = cleanAfter;
          const dollar = nlAfter === "" ? "(?:$|\\/)" : "";
          re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
        }
        if (re !== "" && hasMagic) {
          re = "(?=.)" + re;
        }
        if (addPatternStart) {
          re = patternStart() + re;
        }
        if (options.nocase && !hasMagic && !options.nocaseMagicOnly) {
          hasMagic = pattern.toUpperCase() !== pattern.toLowerCase();
        }
        if (!hasMagic) {
          return globUnescape(re);
        }
        const flags = (options.nocase ? "i" : "") + (uflag ? "u" : "");
        try {
          const ext2 = fastTest ? {
            _glob: pattern,
            _src: re,
            test: fastTest
          } : {
            _glob: pattern,
            _src: re
          };
          return Object.assign(new RegExp("^" + re + "$", flags), ext2);
        } catch (er) {
          this.debug("invalid regexp", er);
          return new RegExp("$.");
        }
      }
      makeRe() {
        if (this.regexp || this.regexp === false)
          return this.regexp;
        const set = this.set;
        if (!set.length) {
          this.regexp = false;
          return this.regexp;
        }
        const options = this.options;
        const twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
        const flags = options.nocase ? "i" : "";
        let re = set.map((pattern) => {
          const pp = pattern.map((p) => typeof p === "string" ? regExpEscape(p) : p === GLOBSTAR ? GLOBSTAR : p._src);
          pp.forEach((p, i) => {
            const next = pp[i + 1];
            const prev = pp[i - 1];
            if (p !== GLOBSTAR || prev === GLOBSTAR) {
              return;
            }
            if (prev === void 0) {
              if (next !== void 0 && next !== GLOBSTAR) {
                pp[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + next;
              } else {
                pp[i] = twoStar;
              }
            } else if (next === void 0) {
              pp[i - 1] = prev + "(?:\\/|" + twoStar + ")?";
            } else if (next !== GLOBSTAR) {
              pp[i - 1] = prev + "(?:\\/|\\/" + twoStar + "\\/)" + next;
              pp[i + 1] = GLOBSTAR;
            }
          });
          return pp.filter((p) => p !== GLOBSTAR).join("/");
        }).join("|");
        re = "^(?:" + re + ")$";
        if (this.negate)
          re = "^(?!" + re + ").*$";
        try {
          this.regexp = new RegExp(re, flags);
        } catch (ex) {
          this.regexp = false;
        }
        return this.regexp;
      }
      slashSplit(p) {
        if (this.preserveMultipleSlashes) {
          return p.split("/");
        } else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
          return ["", ...p.split(/\/+/)];
        } else {
          return p.split(/\/+/);
        }
      }
      match(f, partial = this.partial) {
        this.debug("match", f, this.pattern);
        if (this.comment) {
          return false;
        }
        if (this.empty) {
          return f === "";
        }
        if (f === "/" && partial) {
          return true;
        }
        const options = this.options;
        if (this.isWindows) {
          f = f.split("\\").join("/");
        }
        const ff = this.slashSplit(f);
        this.debug(this.pattern, "split", ff);
        const set = this.set;
        this.debug(this.pattern, "set", set);
        let filename = ff[ff.length - 1];
        if (!filename) {
          for (let i = ff.length - 2; !filename && i >= 0; i--) {
            filename = ff[i];
          }
        }
        for (let i = 0; i < set.length; i++) {
          const pattern = set[i];
          let file = ff;
          if (options.matchBase && pattern.length === 1) {
            file = [filename];
          }
          const hit = this.matchOne(file, pattern, partial);
          if (hit) {
            if (options.flipNegate) {
              return true;
            }
            return !this.negate;
          }
        }
        if (options.flipNegate) {
          return false;
        }
        return this.negate;
      }
      static defaults(def) {
        return minimatch.defaults(def).Minimatch;
      }
    };
    minimatch.Minimatch = Minimatch;
    minimatch.escape = escape;
    minimatch.unescape = unescape;
  }
});

// ../drizzle-orm/dist/entity.js
function is(value, type) {
  if (!value || typeof value !== "object") {
    return false;
  }
  if (value instanceof type) {
    return true;
  }
  if (!Object.prototype.hasOwnProperty.call(type, entityKind)) {
    throw new Error(
      `Class "${type.name ?? "<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`
    );
  }
  let cls = Object.getPrototypeOf(value).constructor;
  if (cls) {
    while (cls) {
      if (entityKind in cls && cls[entityKind] === type[entityKind]) {
        return true;
      }
      cls = Object.getPrototypeOf(cls);
    }
  }
  return false;
}
var entityKind, hasOwnEntityKind;
var init_entity = __esm({
  "../drizzle-orm/dist/entity.js"() {
    "use strict";
    entityKind = Symbol.for("drizzle:entityKind");
    hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind");
  }
});

// ../drizzle-orm/dist/column.js
var _a, Column2;
var init_column = __esm({
  "../drizzle-orm/dist/column.js"() {
    "use strict";
    init_entity();
    _a = entityKind;
    Column2 = class {
      constructor(table6, config) {
        __publicField(this, "name");
        __publicField(this, "keyAsName");
        __publicField(this, "primary");
        __publicField(this, "notNull");
        __publicField(this, "default");
        __publicField(this, "defaultFn");
        __publicField(this, "onUpdateFn");
        __publicField(this, "hasDefault");
        __publicField(this, "isUnique");
        __publicField(this, "uniqueName");
        __publicField(this, "uniqueType");
        __publicField(this, "dataType");
        __publicField(this, "columnType");
        __publicField(this, "enumValues");
        __publicField(this, "generated");
        __publicField(this, "generatedIdentity");
        __publicField(this, "config");
        this.table = table6;
        this.config = config;
        this.name = config.name;
        this.keyAsName = config.keyAsName;
        this.notNull = config.notNull;
        this.default = config.default;
        this.defaultFn = config.defaultFn;
        this.onUpdateFn = config.onUpdateFn;
        this.hasDefault = config.hasDefault;
        this.primary = config.primaryKey;
        this.isUnique = config.isUnique;
        this.uniqueName = config.uniqueName;
        this.uniqueType = config.uniqueType;
        this.dataType = config.dataType;
        this.columnType = config.columnType;
        this.generated = config.generated;
        this.generatedIdentity = config.generatedIdentity;
      }
      mapFromDriverValue(value) {
        return value;
      }
      mapToDriverValue(value) {
        return value;
      }
      // ** @internal */
      shouldDisableInsert() {
        return this.config.generated !== void 0 && this.config.generated.type !== "byDefault";
      }
    };
    __publicField(Column2, _a, "Column");
  }
});

// ../drizzle-orm/dist/column-builder.js
var _a2, ColumnBuilder;
var init_column_builder = __esm({
  "../drizzle-orm/dist/column-builder.js"() {
    "use strict";
    init_entity();
    _a2 = entityKind;
    ColumnBuilder = class {
      constructor(name2, dataType, columnType) {
        __publicField(this, "config");
        /**
         * Alias for {@link $defaultFn}.
         */
        __publicField(this, "$default", this.$defaultFn);
        /**
         * Alias for {@link $onUpdateFn}.
         */
        __publicField(this, "$onUpdate", this.$onUpdateFn);
        this.config = {
          name: name2,
          keyAsName: name2 === "",
          notNull: false,
          default: void 0,
          hasDefault: false,
          primaryKey: false,
          isUnique: false,
          uniqueName: void 0,
          uniqueType: void 0,
          dataType,
          columnType,
          generated: void 0
        };
      }
      /**
       * Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types.
       *
       * @example
       * ```ts
       * const users = pgTable('users', {
       * 	id: integer('id').$type<UserId>().primaryKey(),
       * 	details: json('details').$type<UserDetails>().notNull(),
       * });
       * ```
       */
      $type() {
        return this;
      }
      /**
       * Adds a `not null` clause to the column definition.
       *
       * Affects the `select` model of the table - columns *without* `not null` will be nullable on select.
       */
      notNull() {
        this.config.notNull = true;
        return this;
      }
      /**
       * Adds a `default <value>` clause to the column definition.
       *
       * Affects the `insert` model of the table - columns *with* `default` are optional on insert.
       *
       * If you need to set a dynamic default value, use {@link $defaultFn} instead.
       */
      default(value) {
        this.config.default = value;
        this.config.hasDefault = true;
        return this;
      }
      /**
       * Adds a dynamic default value to the column.
       * The function will be called when the row is inserted, and the returned value will be used as the column value.
       *
       * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.
       */
      $defaultFn(fn) {
        this.config.defaultFn = fn;
        this.config.hasDefault = true;
        return this;
      }
      /**
       * Adds a dynamic update value to the column.
       * The function will be called when the row is updated, and the returned value will be used as the column value if none is provided.
       * If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value.
       *
       * **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.
       */
      $onUpdateFn(fn) {
        this.config.onUpdateFn = fn;
        this.config.hasDefault = true;
        return this;
      }
      /**
       * Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`.
       *
       * In SQLite, `integer primary key` implicitly makes the column auto-incrementing.
       */
      primaryKey() {
        this.config.primaryKey = true;
        this.config.notNull = true;
        return this;
      }
      /** @internal Sets the name of the column to the key within the table definition if a name was not given. */
      setName(name2) {
        if (this.config.name !== "") return;
        this.config.name = name2;
      }
    };
    __publicField(ColumnBuilder, _a2, "ColumnBuilder");
  }
});

// ../drizzle-orm/dist/table.utils.js
var TableName;
var init_table_utils = __esm({
  "../drizzle-orm/dist/table.utils.js"() {
    "use strict";
    TableName = Symbol.for("drizzle:Name");
  }
});

// ../drizzle-orm/dist/pg-core/foreign-keys.js
var _a3, ForeignKeyBuilder, _a4, ForeignKey;
var init_foreign_keys = __esm({
  "../drizzle-orm/dist/pg-core/foreign-keys.js"() {
    "use strict";
    init_entity();
    init_table_utils();
    _a3 = entityKind;
    ForeignKeyBuilder = class {
      constructor(config, actions) {
        /** @internal */
        __publicField(this, "reference");
        /** @internal */
        __publicField(this, "_onUpdate", "no action");
        /** @internal */
        __publicField(this, "_onDelete", "no action");
        this.reference = () => {
          const { name: name2, columns, foreignColumns } = config();
          return { name: name2, columns, foreignTable: foreignColumns[0].table, foreignColumns };
        };
        if (actions) {
          this._onUpdate = actions.onUpdate;
          this._onDelete = actions.onDelete;
        }
      }
      onUpdate(action) {
        this._onUpdate = action === void 0 ? "no action" : action;
        return this;
      }
      onDelete(action) {
        this._onDelete = action === void 0 ? "no action" : action;
        return this;
      }
      /** @internal */
      build(table6) {
        return new ForeignKey(table6, this);
      }
    };
    __publicField(ForeignKeyBuilder, _a3, "PgForeignKeyBuilder");
    _a4 = entityKind;
    ForeignKey = class {
      constructor(table6, builder) {
        __publicField(this, "reference");
        __publicField(this, "onUpdate");
        __publicField(this, "onDelete");
        this.table = table6;
        this.reference = builder.reference;
        this.onUpdate = builder._onUpdate;
        this.onDelete = builder._onDelete;
      }
      getName() {
        const { name: name2, columns, foreignColumns } = this.reference();
        const columnNames = columns.map((column6) => column6.name);
        const foreignColumnNames = foreignColumns.map((column6) => column6.name);
        const chunks = [
          this.table[TableName],
          ...columnNames,
          foreignColumns[0].table[TableName],
          ...foreignColumnNames
        ];
        return name2 ?? `${chunks.join("_")}_fk`;
      }
    };
    __publicField(ForeignKey, _a4, "PgForeignKey");
  }
});

// ../drizzle-orm/dist/tracing-utils.js
function iife(fn, ...args) {
  return fn(...args);
}
var init_tracing_utils = __esm({
  "../drizzle-orm/dist/tracing-utils.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/pg-core/unique-constraint.js
function uniqueKeyName(table6, columns) {
  return `${table6[TableName]}_${columns.join("_")}_unique`;
}
var _a5, UniqueConstraintBuilder, _a6, UniqueOnConstraintBuilder, _a7, UniqueConstraint;
var init_unique_constraint = __esm({
  "../drizzle-orm/dist/pg-core/unique-constraint.js"() {
    "use strict";
    init_entity();
    init_table_utils();
    _a5 = entityKind;
    UniqueConstraintBuilder = class {
      constructor(columns, name2) {
        /** @internal */
        __publicField(this, "columns");
        /** @internal */
        __publicField(this, "nullsNotDistinctConfig", false);
        this.name = name2;
        this.columns = columns;
      }
      nullsNotDistinct() {
        this.nullsNotDistinctConfig = true;
        return this;
      }
      /** @internal */
      build(table6) {
        return new UniqueConstraint(table6, this.columns, this.nullsNotDistinctConfig, this.name);
      }
    };
    __publicField(UniqueConstraintBuilder, _a5, "PgUniqueConstraintBuilder");
    _a6 = entityKind;
    UniqueOnConstraintBuilder = class {
      constructor(name2) {
        /** @internal */
        __publicField(this, "name");
        this.name = name2;
      }
      on(...columns) {
        return new UniqueConstraintBuilder(columns, this.name);
      }
    };
    __publicField(UniqueOnConstraintBuilder, _a6, "PgUniqueOnConstraintBuilder");
    _a7 = entityKind;
    UniqueConstraint = class {
      constructor(table6, columns, nullsNotDistinct, name2) {
        __publicField(this, "columns");
        __publicField(this, "name");
        __publicField(this, "nullsNotDistinct", false);
        this.table = table6;
        this.columns = columns;
        this.name = name2 ?? uniqueKeyName(this.table, this.columns.map((column6) => column6.name));
        this.nullsNotDistinct = nullsNotDistinct;
      }
      getName() {
        return this.name;
      }
    };
    __publicField(UniqueConstraint, _a7, "PgUniqueConstraint");
  }
});

// ../drizzle-orm/dist/pg-core/utils/array.js
function parsePgArrayValue(arrayString, startFrom, inQuotes) {
  for (let i = startFrom; i < arrayString.length; i++) {
    const char4 = arrayString[i];
    if (char4 === "\\") {
      i++;
      continue;
    }
    if (char4 === '"') {
      return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i + 1];
    }
    if (inQuotes) {
      continue;
    }
    if (char4 === "," || char4 === "}") {
      return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i];
    }
  }
  return [arrayString.slice(startFrom).replace(/\\/g, ""), arrayString.length];
}
function parsePgNestedArray(arrayString, startFrom = 0) {
  const result = [];
  let i = startFrom;
  let lastCharIsComma = false;
  while (i < arrayString.length) {
    const char4 = arrayString[i];
    if (char4 === ",") {
      if (lastCharIsComma || i === startFrom) {
        result.push("");
      }
      lastCharIsComma = true;
      i++;
      continue;
    }
    lastCharIsComma = false;
    if (char4 === "\\") {
      i += 2;
      continue;
    }
    if (char4 === '"') {
      const [value2, startFrom2] = parsePgArrayValue(arrayString, i + 1, true);
      result.push(value2);
      i = startFrom2;
      continue;
    }
    if (char4 === "}") {
      return [result, i + 1];
    }
    if (char4 === "{") {
      const [value2, startFrom2] = parsePgNestedArray(arrayString, i + 1);
      result.push(value2);
      i = startFrom2;
      continue;
    }
    const [value, newStartFrom] = parsePgArrayValue(arrayString, i, false);
    result.push(value);
    i = newStartFrom;
  }
  return [result, i];
}
function parsePgArray(arrayString) {
  const [result] = parsePgNestedArray(arrayString, 1);
  return result;
}
function makePgArray(array2) {
  return `{${array2.map((item) => {
    if (Array.isArray(item)) {
      return makePgArray(item);
    }
    if (typeof item === "string") {
      return `"${item.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
    }
    return `${item}`;
  }).join(",")}}`;
}
var init_array = __esm({
  "../drizzle-orm/dist/pg-core/utils/array.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/pg-core/columns/common.js
var _a8, _b, PgColumnBuilder, _a9, _b2, PgColumn, _a10, _b3, ExtraConfigColumn, _a11, IndexedColumn, _a12, _b4, PgArrayBuilder, _a13, _b5, _PgArray, PgArray;
var init_common2 = __esm({
  "../drizzle-orm/dist/pg-core/columns/common.js"() {
    "use strict";
    init_column_builder();
    init_column();
    init_entity();
    init_foreign_keys();
    init_tracing_utils();
    init_unique_constraint();
    init_array();
    PgColumnBuilder = class extends (_b = ColumnBuilder, _a8 = entityKind, _b) {
      constructor() {
        super(...arguments);
        __publicField(this, "foreignKeyConfigs", []);
      }
      array(size) {
        return new PgArrayBuilder(this.config.name, this, size);
      }
      references(ref, actions = {}) {
        this.foreignKeyConfigs.push({ ref, actions });
        return this;
      }
      unique(name2, config) {
        this.config.isUnique = true;
        this.config.uniqueName = name2;
        this.config.uniqueType = config?.nulls;
        return this;
      }
      generatedAlwaysAs(as) {
        this.config.generated = {
          as,
          type: "always",
          mode: "stored"
        };
        return this;
      }
      /** @internal */
      buildForeignKeys(column6, table6) {
        return this.foreignKeyConfigs.map(({ ref, actions }) => {
          return iife(
            (ref2, actions2) => {
              const builder = new ForeignKeyBuilder(() => {
                const foreignColumn = ref2();
                return { columns: [column6], foreignColumns: [foreignColumn] };
              });
              if (actions2.onUpdate) {
                builder.onUpdate(actions2.onUpdate);
              }
              if (actions2.onDelete) {
                builder.onDelete(actions2.onDelete);
              }
              return builder.build(table6);
            },
            ref,
            actions
          );
        });
      }
      /** @internal */
      buildExtraConfigColumn(table6) {
        return new ExtraConfigColumn(table6, this.config);
      }
    };
    __publicField(PgColumnBuilder, _a8, "PgColumnBuilder");
    PgColumn = class extends (_b2 = Column2, _a9 = entityKind, _b2) {
      constructor(table6, config) {
        if (!config.uniqueName) {
          config.uniqueName = uniqueKeyName(table6, [config.name]);
        }
        super(table6, config);
        this.table = table6;
      }
    };
    __publicField(PgColumn, _a9, "PgColumn");
    ExtraConfigColumn = class extends (_b3 = PgColumn, _a10 = entityKind, _b3) {
      constructor() {
        super(...arguments);
        __publicField(this, "indexConfig", {
          order: this.config.order ?? "asc",
          nulls: this.config.nulls ?? "last",
          opClass: this.config.opClass
        });
        __publicField(this, "defaultConfig", {
          order: "asc",
          nulls: "last",
          opClass: void 0
        });
      }
      getSQLType() {
        return this.getSQLType();
      }
      asc() {
        this.indexConfig.order = "asc";
        return this;
      }
      desc() {
        this.indexConfig.order = "desc";
        return this;
      }
      nullsFirst() {
        this.indexConfig.nulls = "first";
        return this;
      }
      nullsLast() {
        this.indexConfig.nulls = "last";
        return this;
      }
      /**
       * ### PostgreSQL documentation quote
       *
       * > An operator class with optional parameters can be specified for each column of an index.
       * The operator class identifies the operators to be used by the index for that column.
       * For example, a B-tree index on four-byte integers would use the int4_ops class;
       * this operator class includes comparison functions for four-byte integers.
       * In practice the default operator class for the column's data type is usually sufficient.
       * The main point of having operator classes is that for some data types, there could be more than one meaningful ordering.
       * For example, we might want to sort a complex-number data type either by absolute value or by real part.
       * We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index.
       * More information about operator classes check:
       *
       * ### Useful links
       * https://www.postgresql.org/docs/current/sql-createindex.html
       *
       * https://www.postgresql.org/docs/current/indexes-opclass.html
       *
       * https://www.postgresql.org/docs/current/xindex.html
       *
       * ### Additional types
       * If you have the `pg_vector` extension installed in your database, you can use the
       * `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types.
       *
       * **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types**
       *
       * @param opClass
       * @returns
       */
      op(opClass) {
        this.indexConfig.opClass = opClass;
        return this;
      }
    };
    __publicField(ExtraConfigColumn, _a10, "ExtraConfigColumn");
    _a11 = entityKind;
    IndexedColumn = class {
      constructor(name2, keyAsName, type, indexConfig) {
        __publicField(this, "name");
        __publicField(this, "keyAsName");
        __publicField(this, "type");
        __publicField(this, "indexConfig");
        this.name = name2;
        this.keyAsName = keyAsName;
        this.type = type;
        this.indexConfig = indexConfig;
      }
    };
    __publicField(IndexedColumn, _a11, "IndexedColumn");
    PgArrayBuilder = class extends (_b4 = PgColumnBuilder, _a12 = entityKind, _b4) {
      constructor(name2, baseBuilder, size) {
        super(name2, "array", "PgArray");
        this.config.baseBuilder = baseBuilder;
        this.config.size = size;
      }
      /** @internal */
      build(table6) {
        const baseColumn = this.config.baseBuilder.build(table6);
        return new PgArray(
          table6,
          this.config,
          baseColumn
        );
      }
    };
    __publicField(PgArrayBuilder, _a12, "PgArrayBuilder");
    _PgArray = class _PgArray extends (_b5 = PgColumn, _a13 = entityKind, _b5) {
      constructor(table6, config, baseColumn, range) {
        super(table6, config);
        __publicField(this, "size");
        this.baseColumn = baseColumn;
        this.range = range;
        this.size = config.size;
      }
      getSQLType() {
        return `${this.baseColumn.getSQLType()}[${typeof this.size === "number" ? this.size : ""}]`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          value = parsePgArray(value);
        }
        return value.map((v) => this.baseColumn.mapFromDriverValue(v));
      }
      mapToDriverValue(value, isNestedArray = false) {
        const a = value.map(
          (v) => v === null ? null : is(this.baseColumn, _PgArray) ? this.baseColumn.mapToDriverValue(v, true) : this.baseColumn.mapToDriverValue(v)
        );
        if (isNestedArray) return a;
        return makePgArray(a);
      }
    };
    __publicField(_PgArray, _a13, "PgArray");
    PgArray = _PgArray;
  }
});

// ../drizzle-orm/dist/pg-core/columns/enum.js
function isPgEnum(obj) {
  return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true;
}
function pgEnumWithSchema(enumName, values, schema5) {
  const enumInstance = Object.assign(
    (name2) => new PgEnumColumnBuilder(name2 ?? "", enumInstance),
    {
      enumName,
      enumValues: values,
      schema: schema5,
      [isPgEnumSym]: true
    }
  );
  return enumInstance;
}
function pgEnumObjectWithSchema(enumName, values, schema5) {
  const enumInstance = Object.assign(
    (name2) => new PgEnumObjectColumnBuilder(name2 ?? "", enumInstance),
    {
      enumName,
      enumValues: Object.values(values),
      schema: schema5,
      [isPgEnumSym]: true
    }
  );
  return enumInstance;
}
var _a14, _b6, PgEnumObjectColumnBuilder, _a15, _b7, PgEnumObjectColumn, isPgEnumSym, _a16, _b8, PgEnumColumnBuilder, _a17, _b9, PgEnumColumn;
var init_enum = __esm({
  "../drizzle-orm/dist/pg-core/columns/enum.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgEnumObjectColumnBuilder = class extends (_b6 = PgColumnBuilder, _a14 = entityKind, _b6) {
      constructor(name2, enumInstance) {
        super(name2, "string", "PgEnumObjectColumn");
        this.config.enum = enumInstance;
      }
      /** @internal */
      build(table6) {
        return new PgEnumObjectColumn(
          table6,
          this.config
        );
      }
    };
    __publicField(PgEnumObjectColumnBuilder, _a14, "PgEnumObjectColumnBuilder");
    PgEnumObjectColumn = class extends (_b7 = PgColumn, _a15 = entityKind, _b7) {
      constructor(table6, config) {
        super(table6, config);
        __publicField(this, "enum");
        __publicField(this, "enumValues", this.config.enum.enumValues);
        this.enum = config.enum;
      }
      getSQLType() {
        return this.enum.enumName;
      }
    };
    __publicField(PgEnumObjectColumn, _a15, "PgEnumObjectColumn");
    isPgEnumSym = Symbol.for("drizzle:isPgEnum");
    PgEnumColumnBuilder = class extends (_b8 = PgColumnBuilder, _a16 = entityKind, _b8) {
      constructor(name2, enumInstance) {
        super(name2, "string", "PgEnumColumn");
        this.config.enum = enumInstance;
      }
      /** @internal */
      build(table6) {
        return new PgEnumColumn(
          table6,
          this.config
        );
      }
    };
    __publicField(PgEnumColumnBuilder, _a16, "PgEnumColumnBuilder");
    PgEnumColumn = class extends (_b9 = PgColumn, _a17 = entityKind, _b9) {
      constructor(table6, config) {
        super(table6, config);
        __publicField(this, "enum", this.config.enum);
        __publicField(this, "enumValues", this.config.enum.enumValues);
        this.enum = config.enum;
      }
      getSQLType() {
        return this.enum.enumName;
      }
    };
    __publicField(PgEnumColumn, _a17, "PgEnumColumn");
  }
});

// ../drizzle-orm/dist/subquery.js
var _a18, Subquery, _a19, _b10, WithSubquery;
var init_subquery = __esm({
  "../drizzle-orm/dist/subquery.js"() {
    "use strict";
    init_entity();
    _a18 = entityKind;
    Subquery = class {
      constructor(sql2, fields, alias, isWith = false, usedTables = []) {
        this._ = {
          brand: "Subquery",
          sql: sql2,
          selectedFields: fields,
          alias,
          isWith,
          usedTables
        };
      }
      // getSQL(): SQL<unknown> {
      // 	return new SQL([this]);
      // }
    };
    __publicField(Subquery, _a18, "Subquery");
    WithSubquery = class extends (_b10 = Subquery, _a19 = entityKind, _b10) {
    };
    __publicField(WithSubquery, _a19, "WithSubquery");
  }
});

// ../drizzle-orm/dist/version.js
var version;
var init_version = __esm({
  "../drizzle-orm/dist/version.js"() {
    "use strict";
    version = "0.44.2";
  }
});

// ../drizzle-orm/dist/tracing.js
var otel, rawTracer, tracer;
var init_tracing = __esm({
  "../drizzle-orm/dist/tracing.js"() {
    "use strict";
    init_tracing_utils();
    init_version();
    tracer = {
      startActiveSpan(name2, fn) {
        if (!otel) {
          return fn();
        }
        if (!rawTracer) {
          rawTracer = otel.trace.getTracer("drizzle-orm", version);
        }
        return iife(
          (otel2, rawTracer2) => rawTracer2.startActiveSpan(
            name2,
            (span) => {
              try {
                return fn(span);
              } catch (e) {
                span.setStatus({
                  code: otel2.SpanStatusCode.ERROR,
                  message: e instanceof Error ? e.message : "Unknown error"
                  // eslint-disable-line no-instanceof/no-instanceof
                });
                throw e;
              } finally {
                span.end();
              }
            }
          ),
          otel,
          rawTracer
        );
      }
    };
  }
});

// ../drizzle-orm/dist/view-common.js
var ViewBaseConfig;
var init_view_common = __esm({
  "../drizzle-orm/dist/view-common.js"() {
    "use strict";
    ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig");
  }
});

// ../drizzle-orm/dist/table.js
function isTable(table6) {
  return typeof table6 === "object" && table6 !== null && IsDrizzleTable in table6;
}
function getTableName(table6) {
  return table6[TableName];
}
function getTableUniqueName(table6) {
  return `${table6[Schema] ?? "public"}.${table6[TableName]}`;
}
var Schema, Columns, ExtraConfigColumns, OriginalName, BaseName, IsAlias, ExtraConfigBuilder, IsDrizzleTable, _a20, _b11, _c, _d, _e, _f, _g, _h, _i, _j, Table2;
var init_table = __esm({
  "../drizzle-orm/dist/table.js"() {
    "use strict";
    init_entity();
    init_table_utils();
    Schema = Symbol.for("drizzle:Schema");
    Columns = Symbol.for("drizzle:Columns");
    ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns");
    OriginalName = Symbol.for("drizzle:OriginalName");
    BaseName = Symbol.for("drizzle:BaseName");
    IsAlias = Symbol.for("drizzle:IsAlias");
    ExtraConfigBuilder = Symbol.for("drizzle:ExtraConfigBuilder");
    IsDrizzleTable = Symbol.for("drizzle:IsDrizzleTable");
    _j = entityKind, _i = TableName, _h = OriginalName, _g = Schema, _f = Columns, _e = ExtraConfigColumns, _d = BaseName, _c = IsAlias, _b11 = IsDrizzleTable, _a20 = ExtraConfigBuilder;
    Table2 = class {
      constructor(name2, schema5, baseName) {
        /**
         * @internal
         * Can be changed if the table is aliased.
         */
        __publicField(this, _i);
        /**
         * @internal
         * Used to store the original name of the table, before any aliasing.
         */
        __publicField(this, _h);
        /** @internal */
        __publicField(this, _g);
        /** @internal */
        __publicField(this, _f);
        /** @internal */
        __publicField(this, _e);
        /**
         *  @internal
         * Used to store the table name before the transformation via the `tableCreator` functions.
         */
        __publicField(this, _d);
        /** @internal */
        __publicField(this, _c, false);
        /** @internal */
        __publicField(this, _b11, true);
        /** @internal */
        __publicField(this, _a20);
        this[TableName] = this[OriginalName] = name2;
        this[Schema] = schema5;
        this[BaseName] = baseName;
      }
    };
    __publicField(Table2, _j, "Table");
    /** @internal */
    __publicField(Table2, "Symbol", {
      Name: TableName,
      Schema,
      OriginalName,
      Columns,
      ExtraConfigColumns,
      BaseName,
      IsAlias,
      ExtraConfigBuilder
    });
  }
});

// ../drizzle-orm/dist/sql/sql.js
function isSQLWrapper(value) {
  return value !== null && value !== void 0 && typeof value.getSQL === "function";
}
function mergeQueries(queries) {
  const result = { sql: "", params: [] };
  for (const query of queries) {
    result.sql += query.sql;
    result.params.push(...query.params);
    if (query.typings?.length) {
      if (!result.typings) {
        result.typings = [];
      }
      result.typings.push(...query.typings);
    }
  }
  return result;
}
function name(value) {
  return new Name(value);
}
function isDriverValueEncoder(value) {
  return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function";
}
function param(value, encoder) {
  return new Param(value, encoder);
}
function sql(strings, ...params) {
  const queryChunks = [];
  if (params.length > 0 || strings.length > 0 && strings[0] !== "") {
    queryChunks.push(new StringChunk(strings[0]));
  }
  for (const [paramIndex, param2] of params.entries()) {
    queryChunks.push(param2, new StringChunk(strings[paramIndex + 1]));
  }
  return new SQL(queryChunks);
}
function placeholder(name2) {
  return new Placeholder(name2);
}
function fillPlaceholders(params, values) {
  return params.map((p) => {
    if (is(p, Placeholder)) {
      if (!(p.name in values)) {
        throw new Error(`No value for placeholder "${p.name}" was provided`);
      }
      return values[p.name];
    }
    if (is(p, Param) && is(p.value, Placeholder)) {
      if (!(p.value.name in values)) {
        throw new Error(`No value for placeholder "${p.value.name}" was provided`);
      }
      return p.encoder.mapToDriverValue(values[p.value.name]);
    }
    return p;
  });
}
function isView(view5) {
  return typeof view5 === "object" && view5 !== null && IsDrizzleView in view5;
}
function getViewName(view5) {
  return view5[ViewBaseConfig].name;
}
var _a21, FakePrimitiveParam, _a22, StringChunk, _a23, _SQL, SQL, _a24, Name, noopDecoder, noopEncoder, noopMapper, _a25, Param, _a26, Placeholder, IsDrizzleView, _a27, _b12, _c2, View3;
var init_sql = __esm({
  "../drizzle-orm/dist/sql/sql.js"() {
    "use strict";
    init_entity();
    init_enum();
    init_subquery();
    init_tracing();
    init_view_common();
    init_column();
    init_table();
    _a21 = entityKind;
    FakePrimitiveParam = class {
    };
    __publicField(FakePrimitiveParam, _a21, "FakePrimitiveParam");
    _a22 = entityKind;
    StringChunk = class {
      constructor(value) {
        __publicField(this, "value");
        this.value = Array.isArray(value) ? value : [value];
      }
      getSQL() {
        return new SQL([this]);
      }
    };
    __publicField(StringChunk, _a22, "StringChunk");
    _a23 = entityKind;
    _SQL = class _SQL {
      constructor(queryChunks) {
        /** @internal */
        __publicField(this, "decoder", noopDecoder);
        __publicField(this, "shouldInlineParams", false);
        /** @internal */
        __publicField(this, "usedTables", []);
        this.queryChunks = queryChunks;
        for (const chunk of queryChunks) {
          if (is(chunk, Table2)) {
            const schemaName = chunk[Table2.Symbol.Schema];
            this.usedTables.push(
              schemaName === void 0 ? chunk[Table2.Symbol.Name] : schemaName + "." + chunk[Table2.Symbol.Name]
            );
          }
        }
      }
      append(query) {
        this.queryChunks.push(...query.queryChunks);
        return this;
      }
      toQuery(config) {
        return tracer.startActiveSpan("drizzle.buildSQL", (span) => {
          const query = this.buildQueryFromSourceParams(this.queryChunks, config);
          span?.setAttributes({
            "drizzle.query.text": query.sql,
            "drizzle.query.params": JSON.stringify(query.params)
          });
          return query;
        });
      }
      buildQueryFromSourceParams(chunks, _config) {
        const config = Object.assign({}, _config, {
          inlineParams: _config.inlineParams || this.shouldInlineParams,
          paramStartIndex: _config.paramStartIndex || { value: 0 }
        });
        const {
          casing: casing2,
          escapeName,
          escapeParam,
          prepareTyping,
          inlineParams,
          paramStartIndex
        } = config;
        return mergeQueries(chunks.map((chunk) => {
          if (is(chunk, StringChunk)) {
            return { sql: chunk.value.join(""), params: [] };
          }
          if (is(chunk, Name)) {
            return { sql: escapeName(chunk.value), params: [] };
          }
          if (chunk === void 0) {
            return { sql: "", params: [] };
          }
          if (Array.isArray(chunk)) {
            const result = [new StringChunk("(")];
            for (const [i, p] of chunk.entries()) {
              result.push(p);
              if (i < chunk.length - 1) {
                result.push(new StringChunk(", "));
              }
            }
            result.push(new StringChunk(")"));
            return this.buildQueryFromSourceParams(result, config);
          }
          if (is(chunk, _SQL)) {
            return this.buildQueryFromSourceParams(chunk.queryChunks, {
              ...config,
              inlineParams: inlineParams || chunk.shouldInlineParams
            });
          }
          if (is(chunk, Table2)) {
            const schemaName = chunk[Table2.Symbol.Schema];
            const tableName = chunk[Table2.Symbol.Name];
            return {
              sql: schemaName === void 0 || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName),
              params: []
            };
          }
          if (is(chunk, Column2)) {
            const columnName = casing2.getColumnCasing(chunk);
            if (_config.invokeSource === "indexes") {
              return { sql: escapeName(columnName), params: [] };
            }
            const schemaName = chunk.table[Table2.Symbol.Schema];
            return {
              sql: chunk.table[IsAlias] || schemaName === void 0 ? escapeName(chunk.table[Table2.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table2.Symbol.Name]) + "." + escapeName(columnName),
              params: []
            };
          }
          if (is(chunk, View3)) {
            const schemaName = chunk[ViewBaseConfig].schema;
            const viewName = chunk[ViewBaseConfig].name;
            return {
              sql: schemaName === void 0 || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName),
              params: []
            };
          }
          if (is(chunk, Param)) {
            if (is(chunk.value, Placeholder)) {
              return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
            }
            const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value);
            if (is(mappedValue, _SQL)) {
              return this.buildQueryFromSourceParams([mappedValue], config);
            }
            if (inlineParams) {
              return { sql: this.mapInlineParam(mappedValue, config), params: [] };
            }
            let typings = ["none"];
            if (prepareTyping) {
              typings = [prepareTyping(chunk.encoder)];
            }
            return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings };
          }
          if (is(chunk, Placeholder)) {
            return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
          }
          if (is(chunk, _SQL.Aliased) && chunk.fieldAlias !== void 0) {
            return { sql: escapeName(chunk.fieldAlias), params: [] };
          }
          if (is(chunk, Subquery)) {
            if (chunk._.isWith) {
              return { sql: escapeName(chunk._.alias), params: [] };
            }
            return this.buildQueryFromSourceParams([
              new StringChunk("("),
              chunk._.sql,
              new StringChunk(") "),
              new Name(chunk._.alias)
            ], config);
          }
          if (isPgEnum(chunk)) {
            if (chunk.schema) {
              return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] };
            }
            return { sql: escapeName(chunk.enumName), params: [] };
          }
          if (isSQLWrapper(chunk)) {
            if (chunk.shouldOmitSQLParens?.()) {
              return this.buildQueryFromSourceParams([chunk.getSQL()], config);
            }
            return this.buildQueryFromSourceParams([
              new StringChunk("("),
              chunk.getSQL(),
              new StringChunk(")")
            ], config);
          }
          if (inlineParams) {
            return { sql: this.mapInlineParam(chunk, config), params: [] };
          }
          return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] };
        }));
      }
      mapInlineParam(chunk, { escapeString }) {
        if (chunk === null) {
          return "null";
        }
        if (typeof chunk === "number" || typeof chunk === "boolean") {
          return chunk.toString();
        }
        if (typeof chunk === "string") {
          return escapeString(chunk);
        }
        if (typeof chunk === "object") {
          const mappedValueAsString = chunk.toString();
          if (mappedValueAsString === "[object Object]") {
            return escapeString(JSON.stringify(chunk));
          }
          return escapeString(mappedValueAsString);
        }
        throw new Error("Unexpected param value: " + chunk);
      }
      getSQL() {
        return this;
      }
      as(alias) {
        if (alias === void 0) {
          return this;
        }
        return new _SQL.Aliased(this, alias);
      }
      mapWith(decoder) {
        this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder;
        return this;
      }
      inlineParams() {
        this.shouldInlineParams = true;
        return this;
      }
      /**
       * This method is used to conditionally include a part of the query.
       *
       * @param condition - Condition to check
       * @returns itself if the condition is `true`, otherwise `undefined`
       */
      if(condition) {
        return condition ? this : void 0;
      }
    };
    __publicField(_SQL, _a23, "SQL");
    SQL = _SQL;
    _a24 = entityKind;
    Name = class {
      constructor(value) {
        __publicField(this, "brand");
        this.value = value;
      }
      getSQL() {
        return new SQL([this]);
      }
    };
    __publicField(Name, _a24, "Name");
    noopDecoder = {
      mapFromDriverValue: (value) => value
    };
    noopEncoder = {
      mapToDriverValue: (value) => value
    };
    noopMapper = {
      ...noopDecoder,
      ...noopEncoder
    };
    _a25 = entityKind;
    Param = class {
      /**
       * @param value - Parameter value
       * @param encoder - Encoder to convert the value to a driver parameter
       */
      constructor(value, encoder = noopEncoder) {
        __publicField(this, "brand");
        this.value = value;
        this.encoder = encoder;
      }
      getSQL() {
        return new SQL([this]);
      }
    };
    __publicField(Param, _a25, "Param");
    ((sql2) => {
      function empty() {
        return new SQL([]);
      }
      sql2.empty = empty;
      function fromList(list) {
        return new SQL(list);
      }
      sql2.fromList = fromList;
      function raw(str) {
        return new SQL([new StringChunk(str)]);
      }
      sql2.raw = raw;
      function join(chunks, separator) {
        const result = [];
        for (const [i, chunk] of chunks.entries()) {
          if (i > 0 && separator !== void 0) {
            result.push(separator);
          }
          result.push(chunk);
        }
        return new SQL(result);
      }
      sql2.join = join;
      function identifier(value) {
        return new Name(value);
      }
      sql2.identifier = identifier;
      function placeholder2(name2) {
        return new Placeholder(name2);
      }
      sql2.placeholder = placeholder2;
      function param2(value, encoder) {
        return new Param(value, encoder);
      }
      sql2.param = param2;
    })(sql || (sql = {}));
    ((SQL2) => {
      var _a437;
      _a437 = entityKind;
      const _Aliased = class _Aliased {
        constructor(sql2, fieldAlias) {
          /** @internal */
          __publicField(this, "isSelectionField", false);
          this.sql = sql2;
          this.fieldAlias = fieldAlias;
        }
        getSQL() {
          return this.sql;
        }
        /** @internal */
        clone() {
          return new _Aliased(this.sql, this.fieldAlias);
        }
      };
      __publicField(_Aliased, _a437, "SQL.Aliased");
      let Aliased = _Aliased;
      SQL2.Aliased = Aliased;
    })(SQL || (SQL = {}));
    _a26 = entityKind;
    Placeholder = class {
      constructor(name2) {
        this.name = name2;
      }
      getSQL() {
        return new SQL([this]);
      }
    };
    __publicField(Placeholder, _a26, "Placeholder");
    IsDrizzleView = Symbol.for("drizzle:IsDrizzleView");
    _c2 = entityKind, _b12 = ViewBaseConfig, _a27 = IsDrizzleView;
    View3 = class {
      constructor({ name: name2, schema: schema5, selectedFields, query }) {
        /** @internal */
        __publicField(this, _b12);
        /** @internal */
        __publicField(this, _a27, true);
        this[ViewBaseConfig] = {
          name: name2,
          originalName: name2,
          schema: schema5,
          selectedFields,
          query,
          isExisting: !query,
          isAlias: false
        };
      }
      getSQL() {
        return new SQL([this]);
      }
    };
    __publicField(View3, _c2, "View");
    Column2.prototype.getSQL = function() {
      return new SQL([this]);
    };
    Table2.prototype.getSQL = function() {
      return new SQL([this]);
    };
    Subquery.prototype.getSQL = function() {
      return new SQL([this]);
    };
  }
});

// ../drizzle-orm/dist/alias.js
function aliasedTable(table6, tableAlias) {
  return new Proxy(table6, new TableAliasProxyHandler(tableAlias, false));
}
function aliasedRelation(relation, tableAlias) {
  return new Proxy(relation, new RelationTableAliasProxyHandler(tableAlias));
}
function aliasedTableColumn(column6, tableAlias) {
  return new Proxy(
    column6,
    new ColumnAliasProxyHandler(new Proxy(column6.table, new TableAliasProxyHandler(tableAlias, false)))
  );
}
function mapColumnsInAliasedSQLToAlias(query, alias) {
  return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias);
}
function mapColumnsInSQLToAlias(query, alias) {
  return sql.join(query.queryChunks.map((c) => {
    if (is(c, Column2)) {
      return aliasedTableColumn(c, alias);
    }
    if (is(c, SQL)) {
      return mapColumnsInSQLToAlias(c, alias);
    }
    if (is(c, SQL.Aliased)) {
      return mapColumnsInAliasedSQLToAlias(c, alias);
    }
    return c;
  }));
}
var _a28, ColumnAliasProxyHandler, _a29, TableAliasProxyHandler, _a30, RelationTableAliasProxyHandler;
var init_alias = __esm({
  "../drizzle-orm/dist/alias.js"() {
    "use strict";
    init_column();
    init_entity();
    init_sql();
    init_table();
    init_view_common();
    _a28 = entityKind;
    ColumnAliasProxyHandler = class {
      constructor(table6) {
        this.table = table6;
      }
      get(columnObj, prop) {
        if (prop === "table") {
          return this.table;
        }
        return columnObj[prop];
      }
    };
    __publicField(ColumnAliasProxyHandler, _a28, "ColumnAliasProxyHandler");
    _a29 = entityKind;
    TableAliasProxyHandler = class {
      constructor(alias, replaceOriginalName) {
        this.alias = alias;
        this.replaceOriginalName = replaceOriginalName;
      }
      get(target, prop) {
        if (prop === Table2.Symbol.IsAlias) {
          return true;
        }
        if (prop === Table2.Symbol.Name) {
          return this.alias;
        }
        if (this.replaceOriginalName && prop === Table2.Symbol.OriginalName) {
          return this.alias;
        }
        if (prop === ViewBaseConfig) {
          return {
            ...target[ViewBaseConfig],
            name: this.alias,
            isAlias: true
          };
        }
        if (prop === Table2.Symbol.Columns) {
          const columns = target[Table2.Symbol.Columns];
          if (!columns) {
            return columns;
          }
          const proxiedColumns = {};
          Object.keys(columns).map((key) => {
            proxiedColumns[key] = new Proxy(
              columns[key],
              new ColumnAliasProxyHandler(new Proxy(target, this))
            );
          });
          return proxiedColumns;
        }
        const value = target[prop];
        if (is(value, Column2)) {
          return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this)));
        }
        return value;
      }
    };
    __publicField(TableAliasProxyHandler, _a29, "TableAliasProxyHandler");
    _a30 = entityKind;
    RelationTableAliasProxyHandler = class {
      constructor(alias) {
        this.alias = alias;
      }
      get(target, prop) {
        if (prop === "sourceTable") {
          return aliasedTable(target.sourceTable, this.alias);
        }
        return target[prop];
      }
    };
    __publicField(RelationTableAliasProxyHandler, _a30, "RelationTableAliasProxyHandler");
  }
});

// ../drizzle-orm/dist/errors.js
var _a31, _b13, DrizzleError, _a32, _b14, TransactionRollbackError;
var init_errors2 = __esm({
  "../drizzle-orm/dist/errors.js"() {
    "use strict";
    init_entity();
    DrizzleError = class extends (_b13 = Error, _a31 = entityKind, _b13) {
      constructor({ message, cause }) {
        super(message);
        this.name = "DrizzleError";
        this.cause = cause;
      }
    };
    __publicField(DrizzleError, _a31, "DrizzleError");
    TransactionRollbackError = class extends (_b14 = DrizzleError, _a32 = entityKind, _b14) {
      constructor() {
        super({ message: "Rollback" });
      }
    };
    __publicField(TransactionRollbackError, _a32, "TransactionRollbackError");
  }
});

// ../drizzle-orm/dist/logger.js
var _a33, ConsoleLogWriter, _a34, DefaultLogger, _a35, NoopLogger;
var init_logger = __esm({
  "../drizzle-orm/dist/logger.js"() {
    "use strict";
    init_entity();
    _a33 = entityKind;
    ConsoleLogWriter = class {
      write(message) {
        console.log(message);
      }
    };
    __publicField(ConsoleLogWriter, _a33, "ConsoleLogWriter");
    _a34 = entityKind;
    DefaultLogger = class {
      constructor(config) {
        __publicField(this, "writer");
        this.writer = config?.writer ?? new ConsoleLogWriter();
      }
      logQuery(query, params) {
        const stringifiedParams = params.map((p) => {
          try {
            return JSON.stringify(p);
          } catch {
            return String(p);
          }
        });
        const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : "";
        this.writer.write(`Query: ${query}${paramsStr}`);
      }
    };
    __publicField(DefaultLogger, _a34, "DefaultLogger");
    _a35 = entityKind;
    NoopLogger = class {
      logQuery() {
      }
    };
    __publicField(NoopLogger, _a35, "NoopLogger");
  }
});

// ../drizzle-orm/dist/operations.js
var init_operations = __esm({
  "../drizzle-orm/dist/operations.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/query-promise.js
var _a36, _b15, QueryPromise;
var init_query_promise = __esm({
  "../drizzle-orm/dist/query-promise.js"() {
    "use strict";
    init_entity();
    _b15 = entityKind, _a36 = Symbol.toStringTag;
    QueryPromise = class {
      constructor() {
        __publicField(this, _a36, "QueryPromise");
      }
      catch(onRejected) {
        return this.then(void 0, onRejected);
      }
      finally(onFinally) {
        return this.then(
          (value) => {
            onFinally?.();
            return value;
          },
          (reason) => {
            onFinally?.();
            throw reason;
          }
        );
      }
      then(onFulfilled, onRejected) {
        return this.execute().then(onFulfilled, onRejected);
      }
    };
    __publicField(QueryPromise, _b15, "QueryPromise");
  }
});

// ../drizzle-orm/dist/utils.js
function mapResultRow(columns, row, joinsNotNullableMap) {
  const nullifyMap = {};
  const result = columns.reduce(
    (result2, { path: path2, field }, columnIndex) => {
      let decoder;
      if (is(field, Column2)) {
        decoder = field;
      } else if (is(field, SQL)) {
        decoder = field.decoder;
      } else {
        decoder = field.sql.decoder;
      }
      let node = result2;
      for (const [pathChunkIndex, pathChunk] of path2.entries()) {
        if (pathChunkIndex < path2.length - 1) {
          if (!(pathChunk in node)) {
            node[pathChunk] = {};
          }
          node = node[pathChunk];
        } else {
          const rawValue = row[columnIndex];
          const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue);
          if (joinsNotNullableMap && is(field, Column2) && path2.length === 2) {
            const objectName = path2[0];
            if (!(objectName in nullifyMap)) {
              nullifyMap[objectName] = value === null ? getTableName(field.table) : false;
            } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) {
              nullifyMap[objectName] = false;
            }
          }
        }
      }
      return result2;
    },
    {}
  );
  if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {
    for (const [objectName, tableName] of Object.entries(nullifyMap)) {
      if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) {
        result[objectName] = null;
      }
    }
  }
  return result;
}
function orderSelectedFields(fields, pathPrefix) {
  return Object.entries(fields).reduce((result, [name2, field]) => {
    if (typeof name2 !== "string") {
      return result;
    }
    const newPath = pathPrefix ? [...pathPrefix, name2] : [name2];
    if (is(field, Column2) || is(field, SQL) || is(field, SQL.Aliased)) {
      result.push({ path: newPath, field });
    } else if (is(field, Table2)) {
      result.push(...orderSelectedFields(field[Table2.Symbol.Columns], newPath));
    } else {
      result.push(...orderSelectedFields(field, newPath));
    }
    return result;
  }, []);
}
function haveSameKeys(left, right) {
  const leftKeys = Object.keys(left);
  const rightKeys = Object.keys(right);
  if (leftKeys.length !== rightKeys.length) {
    return false;
  }
  for (const [index6, key] of leftKeys.entries()) {
    if (key !== rightKeys[index6]) {
      return false;
    }
  }
  return true;
}
function mapUpdateSet(table6, values) {
  const entries = Object.entries(values).filter(([, value]) => value !== void 0).map(([key, value]) => {
    if (is(value, SQL) || is(value, Column2)) {
      return [key, value];
    } else {
      return [key, new Param(value, table6[Table2.Symbol.Columns][key])];
    }
  });
  if (entries.length === 0) {
    throw new Error("No values to set");
  }
  return Object.fromEntries(entries);
}
function applyMixins(baseClass, extendedClasses) {
  for (const extendedClass of extendedClasses) {
    for (const name2 of Object.getOwnPropertyNames(extendedClass.prototype)) {
      if (name2 === "constructor") continue;
      Object.defineProperty(
        baseClass.prototype,
        name2,
        Object.getOwnPropertyDescriptor(extendedClass.prototype, name2) || /* @__PURE__ */ Object.create(null)
      );
    }
  }
}
function getTableColumns(table6) {
  return table6[Table2.Symbol.Columns];
}
function getViewSelectedFields(view5) {
  return view5[ViewBaseConfig].selectedFields;
}
function getTableLikeName(table6) {
  return is(table6, Subquery) ? table6._.alias : is(table6, View3) ? table6[ViewBaseConfig].name : is(table6, SQL) ? void 0 : table6[Table2.Symbol.IsAlias] ? table6[Table2.Symbol.Name] : table6[Table2.Symbol.BaseName];
}
function getColumnNameAndConfig(a, b) {
  return {
    name: typeof a === "string" && a.length > 0 ? a : "",
    config: typeof a === "object" ? a : b
  };
}
function isConfig(data) {
  if (typeof data !== "object" || data === null) return false;
  if (data.constructor.name !== "Object") return false;
  if ("logger" in data) {
    const type = typeof data["logger"];
    if (type !== "boolean" && (type !== "object" || typeof data["logger"]["logQuery"] !== "function") && type !== "undefined") return false;
    return true;
  }
  if ("schema" in data) {
    const type = typeof data["schema"];
    if (type !== "object" && type !== "undefined") return false;
    return true;
  }
  if ("casing" in data) {
    const type = typeof data["casing"];
    if (type !== "string" && type !== "undefined") return false;
    return true;
  }
  if ("mode" in data) {
    if (data["mode"] !== "default" || data["mode"] !== "planetscale" || data["mode"] !== void 0) return false;
    return true;
  }
  if ("connection" in data) {
    const type = typeof data["connection"];
    if (type !== "string" && type !== "object" && type !== "undefined") return false;
    return true;
  }
  if ("client" in data) {
    const type = typeof data["client"];
    if (type !== "object" && type !== "function" && type !== "undefined") return false;
    return true;
  }
  if (Object.keys(data).length === 0) return true;
  return false;
}
var init_utils2 = __esm({
  "../drizzle-orm/dist/utils.js"() {
    "use strict";
    init_column();
    init_entity();
    init_sql();
    init_subquery();
    init_table();
    init_view_common();
  }
});

// ../drizzle-orm/dist/pg-core/columns/int.common.js
var _a37, _b16, PgIntColumnBaseBuilder;
var init_int_common = __esm({
  "../drizzle-orm/dist/pg-core/columns/int.common.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgIntColumnBaseBuilder = class extends (_b16 = PgColumnBuilder, _a37 = entityKind, _b16) {
      generatedAlwaysAsIdentity(sequence) {
        if (sequence) {
          const { name: name2, ...options } = sequence;
          this.config.generatedIdentity = {
            type: "always",
            sequenceName: name2,
            sequenceOptions: options
          };
        } else {
          this.config.generatedIdentity = {
            type: "always"
          };
        }
        this.config.hasDefault = true;
        this.config.notNull = true;
        return this;
      }
      generatedByDefaultAsIdentity(sequence) {
        if (sequence) {
          const { name: name2, ...options } = sequence;
          this.config.generatedIdentity = {
            type: "byDefault",
            sequenceName: name2,
            sequenceOptions: options
          };
        } else {
          this.config.generatedIdentity = {
            type: "byDefault"
          };
        }
        this.config.hasDefault = true;
        this.config.notNull = true;
        return this;
      }
    };
    __publicField(PgIntColumnBaseBuilder, _a37, "PgIntColumnBaseBuilder");
  }
});

// ../drizzle-orm/dist/pg-core/columns/bigint.js
function bigint(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config.mode === "number") {
    return new PgBigInt53Builder(name2);
  }
  return new PgBigInt64Builder(name2);
}
var _a38, _b17, PgBigInt53Builder, _a39, _b18, PgBigInt53, _a40, _b19, PgBigInt64Builder, _a41, _b20, PgBigInt64;
var init_bigint = __esm({
  "../drizzle-orm/dist/pg-core/columns/bigint.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    init_int_common();
    PgBigInt53Builder = class extends (_b17 = PgIntColumnBaseBuilder, _a38 = entityKind, _b17) {
      constructor(name2) {
        super(name2, "number", "PgBigInt53");
      }
      /** @internal */
      build(table6) {
        return new PgBigInt53(table6, this.config);
      }
    };
    __publicField(PgBigInt53Builder, _a38, "PgBigInt53Builder");
    PgBigInt53 = class extends (_b18 = PgColumn, _a39 = entityKind, _b18) {
      getSQLType() {
        return "bigint";
      }
      mapFromDriverValue(value) {
        if (typeof value === "number") {
          return value;
        }
        return Number(value);
      }
    };
    __publicField(PgBigInt53, _a39, "PgBigInt53");
    PgBigInt64Builder = class extends (_b19 = PgIntColumnBaseBuilder, _a40 = entityKind, _b19) {
      constructor(name2) {
        super(name2, "bigint", "PgBigInt64");
      }
      /** @internal */
      build(table6) {
        return new PgBigInt64(
          table6,
          this.config
        );
      }
    };
    __publicField(PgBigInt64Builder, _a40, "PgBigInt64Builder");
    PgBigInt64 = class extends (_b20 = PgColumn, _a41 = entityKind, _b20) {
      getSQLType() {
        return "bigint";
      }
      // eslint-disable-next-line unicorn/prefer-native-coercion-functions
      mapFromDriverValue(value) {
        return BigInt(value);
      }
    };
    __publicField(PgBigInt64, _a41, "PgBigInt64");
  }
});

// ../drizzle-orm/dist/pg-core/columns/bigserial.js
function bigserial(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config.mode === "number") {
    return new PgBigSerial53Builder(name2);
  }
  return new PgBigSerial64Builder(name2);
}
var _a42, _b21, PgBigSerial53Builder, _a43, _b22, PgBigSerial53, _a44, _b23, PgBigSerial64Builder, _a45, _b24, PgBigSerial64;
var init_bigserial = __esm({
  "../drizzle-orm/dist/pg-core/columns/bigserial.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgBigSerial53Builder = class extends (_b21 = PgColumnBuilder, _a42 = entityKind, _b21) {
      constructor(name2) {
        super(name2, "number", "PgBigSerial53");
        this.config.hasDefault = true;
        this.config.notNull = true;
      }
      /** @internal */
      build(table6) {
        return new PgBigSerial53(
          table6,
          this.config
        );
      }
    };
    __publicField(PgBigSerial53Builder, _a42, "PgBigSerial53Builder");
    PgBigSerial53 = class extends (_b22 = PgColumn, _a43 = entityKind, _b22) {
      getSQLType() {
        return "bigserial";
      }
      mapFromDriverValue(value) {
        if (typeof value === "number") {
          return value;
        }
        return Number(value);
      }
    };
    __publicField(PgBigSerial53, _a43, "PgBigSerial53");
    PgBigSerial64Builder = class extends (_b23 = PgColumnBuilder, _a44 = entityKind, _b23) {
      constructor(name2) {
        super(name2, "bigint", "PgBigSerial64");
        this.config.hasDefault = true;
      }
      /** @internal */
      build(table6) {
        return new PgBigSerial64(
          table6,
          this.config
        );
      }
    };
    __publicField(PgBigSerial64Builder, _a44, "PgBigSerial64Builder");
    PgBigSerial64 = class extends (_b24 = PgColumn, _a45 = entityKind, _b24) {
      getSQLType() {
        return "bigserial";
      }
      // eslint-disable-next-line unicorn/prefer-native-coercion-functions
      mapFromDriverValue(value) {
        return BigInt(value);
      }
    };
    __publicField(PgBigSerial64, _a45, "PgBigSerial64");
  }
});

// ../drizzle-orm/dist/pg-core/columns/boolean.js
function boolean(name2) {
  return new PgBooleanBuilder(name2 ?? "");
}
var _a46, _b25, PgBooleanBuilder, _a47, _b26, PgBoolean;
var init_boolean = __esm({
  "../drizzle-orm/dist/pg-core/columns/boolean.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgBooleanBuilder = class extends (_b25 = PgColumnBuilder, _a46 = entityKind, _b25) {
      constructor(name2) {
        super(name2, "boolean", "PgBoolean");
      }
      /** @internal */
      build(table6) {
        return new PgBoolean(table6, this.config);
      }
    };
    __publicField(PgBooleanBuilder, _a46, "PgBooleanBuilder");
    PgBoolean = class extends (_b26 = PgColumn, _a47 = entityKind, _b26) {
      getSQLType() {
        return "boolean";
      }
    };
    __publicField(PgBoolean, _a47, "PgBoolean");
  }
});

// ../drizzle-orm/dist/pg-core/columns/char.js
function char(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgCharBuilder(name2, config);
}
var _a48, _b27, PgCharBuilder, _a49, _b28, PgChar;
var init_char = __esm({
  "../drizzle-orm/dist/pg-core/columns/char.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgCharBuilder = class extends (_b27 = PgColumnBuilder, _a48 = entityKind, _b27) {
      constructor(name2, config) {
        super(name2, "string", "PgChar");
        this.config.length = config.length;
        this.config.enumValues = config.enum;
      }
      /** @internal */
      build(table6) {
        return new PgChar(
          table6,
          this.config
        );
      }
    };
    __publicField(PgCharBuilder, _a48, "PgCharBuilder");
    PgChar = class extends (_b28 = PgColumn, _a49 = entityKind, _b28) {
      constructor() {
        super(...arguments);
        __publicField(this, "length", this.config.length);
        __publicField(this, "enumValues", this.config.enumValues);
      }
      getSQLType() {
        return this.length === void 0 ? `char` : `char(${this.length})`;
      }
    };
    __publicField(PgChar, _a49, "PgChar");
  }
});

// ../drizzle-orm/dist/pg-core/columns/cidr.js
function cidr(name2) {
  return new PgCidrBuilder(name2 ?? "");
}
var _a50, _b29, PgCidrBuilder, _a51, _b30, PgCidr;
var init_cidr = __esm({
  "../drizzle-orm/dist/pg-core/columns/cidr.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgCidrBuilder = class extends (_b29 = PgColumnBuilder, _a50 = entityKind, _b29) {
      constructor(name2) {
        super(name2, "string", "PgCidr");
      }
      /** @internal */
      build(table6) {
        return new PgCidr(table6, this.config);
      }
    };
    __publicField(PgCidrBuilder, _a50, "PgCidrBuilder");
    PgCidr = class extends (_b30 = PgColumn, _a51 = entityKind, _b30) {
      getSQLType() {
        return "cidr";
      }
    };
    __publicField(PgCidr, _a51, "PgCidr");
  }
});

// ../drizzle-orm/dist/pg-core/columns/custom.js
function customType(customTypeParams) {
  return (a, b) => {
    const { name: name2, config } = getColumnNameAndConfig(a, b);
    return new PgCustomColumnBuilder(name2, config, customTypeParams);
  };
}
var _a52, _b31, PgCustomColumnBuilder, _a53, _b32, PgCustomColumn;
var init_custom = __esm({
  "../drizzle-orm/dist/pg-core/columns/custom.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgCustomColumnBuilder = class extends (_b31 = PgColumnBuilder, _a52 = entityKind, _b31) {
      constructor(name2, fieldConfig, customTypeParams) {
        super(name2, "custom", "PgCustomColumn");
        this.config.fieldConfig = fieldConfig;
        this.config.customTypeParams = customTypeParams;
      }
      /** @internal */
      build(table6) {
        return new PgCustomColumn(
          table6,
          this.config
        );
      }
    };
    __publicField(PgCustomColumnBuilder, _a52, "PgCustomColumnBuilder");
    PgCustomColumn = class extends (_b32 = PgColumn, _a53 = entityKind, _b32) {
      constructor(table6, config) {
        super(table6, config);
        __publicField(this, "sqlName");
        __publicField(this, "mapTo");
        __publicField(this, "mapFrom");
        this.sqlName = config.customTypeParams.dataType(config.fieldConfig);
        this.mapTo = config.customTypeParams.toDriver;
        this.mapFrom = config.customTypeParams.fromDriver;
      }
      getSQLType() {
        return this.sqlName;
      }
      mapFromDriverValue(value) {
        return typeof this.mapFrom === "function" ? this.mapFrom(value) : value;
      }
      mapToDriverValue(value) {
        return typeof this.mapTo === "function" ? this.mapTo(value) : value;
      }
    };
    __publicField(PgCustomColumn, _a53, "PgCustomColumn");
  }
});

// ../drizzle-orm/dist/pg-core/columns/date.common.js
var _a54, _b33, PgDateColumnBaseBuilder;
var init_date_common = __esm({
  "../drizzle-orm/dist/pg-core/columns/date.common.js"() {
    "use strict";
    init_entity();
    init_sql();
    init_common2();
    PgDateColumnBaseBuilder = class extends (_b33 = PgColumnBuilder, _a54 = entityKind, _b33) {
      defaultNow() {
        return this.default(sql`now()`);
      }
    };
    __publicField(PgDateColumnBaseBuilder, _a54, "PgDateColumnBaseBuilder");
  }
});

// ../drizzle-orm/dist/pg-core/columns/date.js
function date(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config?.mode === "date") {
    return new PgDateBuilder(name2);
  }
  return new PgDateStringBuilder(name2);
}
var _a55, _b34, PgDateBuilder, _a56, _b35, PgDate, _a57, _b36, PgDateStringBuilder, _a58, _b37, PgDateString;
var init_date = __esm({
  "../drizzle-orm/dist/pg-core/columns/date.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    init_date_common();
    PgDateBuilder = class extends (_b34 = PgDateColumnBaseBuilder, _a55 = entityKind, _b34) {
      constructor(name2) {
        super(name2, "date", "PgDate");
      }
      /** @internal */
      build(table6) {
        return new PgDate(table6, this.config);
      }
    };
    __publicField(PgDateBuilder, _a55, "PgDateBuilder");
    PgDate = class extends (_b35 = PgColumn, _a56 = entityKind, _b35) {
      getSQLType() {
        return "date";
      }
      mapFromDriverValue(value) {
        return new Date(value);
      }
      mapToDriverValue(value) {
        return value.toISOString();
      }
    };
    __publicField(PgDate, _a56, "PgDate");
    PgDateStringBuilder = class extends (_b36 = PgDateColumnBaseBuilder, _a57 = entityKind, _b36) {
      constructor(name2) {
        super(name2, "string", "PgDateString");
      }
      /** @internal */
      build(table6) {
        return new PgDateString(
          table6,
          this.config
        );
      }
    };
    __publicField(PgDateStringBuilder, _a57, "PgDateStringBuilder");
    PgDateString = class extends (_b37 = PgColumn, _a58 = entityKind, _b37) {
      getSQLType() {
        return "date";
      }
    };
    __publicField(PgDateString, _a58, "PgDateString");
  }
});

// ../drizzle-orm/dist/pg-core/columns/double-precision.js
function doublePrecision(name2) {
  return new PgDoublePrecisionBuilder(name2 ?? "");
}
var _a59, _b38, PgDoublePrecisionBuilder, _a60, _b39, PgDoublePrecision;
var init_double_precision = __esm({
  "../drizzle-orm/dist/pg-core/columns/double-precision.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgDoublePrecisionBuilder = class extends (_b38 = PgColumnBuilder, _a59 = entityKind, _b38) {
      constructor(name2) {
        super(name2, "number", "PgDoublePrecision");
      }
      /** @internal */
      build(table6) {
        return new PgDoublePrecision(
          table6,
          this.config
        );
      }
    };
    __publicField(PgDoublePrecisionBuilder, _a59, "PgDoublePrecisionBuilder");
    PgDoublePrecision = class extends (_b39 = PgColumn, _a60 = entityKind, _b39) {
      getSQLType() {
        return "double precision";
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number.parseFloat(value);
        }
        return value;
      }
    };
    __publicField(PgDoublePrecision, _a60, "PgDoublePrecision");
  }
});

// ../drizzle-orm/dist/pg-core/columns/inet.js
function inet(name2) {
  return new PgInetBuilder(name2 ?? "");
}
var _a61, _b40, PgInetBuilder, _a62, _b41, PgInet;
var init_inet = __esm({
  "../drizzle-orm/dist/pg-core/columns/inet.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgInetBuilder = class extends (_b40 = PgColumnBuilder, _a61 = entityKind, _b40) {
      constructor(name2) {
        super(name2, "string", "PgInet");
      }
      /** @internal */
      build(table6) {
        return new PgInet(table6, this.config);
      }
    };
    __publicField(PgInetBuilder, _a61, "PgInetBuilder");
    PgInet = class extends (_b41 = PgColumn, _a62 = entityKind, _b41) {
      getSQLType() {
        return "inet";
      }
    };
    __publicField(PgInet, _a62, "PgInet");
  }
});

// ../drizzle-orm/dist/pg-core/columns/integer.js
function integer(name2) {
  return new PgIntegerBuilder(name2 ?? "");
}
var _a63, _b42, PgIntegerBuilder, _a64, _b43, PgInteger;
var init_integer = __esm({
  "../drizzle-orm/dist/pg-core/columns/integer.js"() {
    "use strict";
    init_entity();
    init_common2();
    init_int_common();
    PgIntegerBuilder = class extends (_b42 = PgIntColumnBaseBuilder, _a63 = entityKind, _b42) {
      constructor(name2) {
        super(name2, "number", "PgInteger");
      }
      /** @internal */
      build(table6) {
        return new PgInteger(table6, this.config);
      }
    };
    __publicField(PgIntegerBuilder, _a63, "PgIntegerBuilder");
    PgInteger = class extends (_b43 = PgColumn, _a64 = entityKind, _b43) {
      getSQLType() {
        return "integer";
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number.parseInt(value);
        }
        return value;
      }
    };
    __publicField(PgInteger, _a64, "PgInteger");
  }
});

// ../drizzle-orm/dist/pg-core/columns/interval.js
function interval(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgIntervalBuilder(name2, config);
}
var _a65, _b44, PgIntervalBuilder, _a66, _b45, PgInterval;
var init_interval = __esm({
  "../drizzle-orm/dist/pg-core/columns/interval.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgIntervalBuilder = class extends (_b44 = PgColumnBuilder, _a65 = entityKind, _b44) {
      constructor(name2, intervalConfig) {
        super(name2, "string", "PgInterval");
        this.config.intervalConfig = intervalConfig;
      }
      /** @internal */
      build(table6) {
        return new PgInterval(table6, this.config);
      }
    };
    __publicField(PgIntervalBuilder, _a65, "PgIntervalBuilder");
    PgInterval = class extends (_b45 = PgColumn, _a66 = entityKind, _b45) {
      constructor() {
        super(...arguments);
        __publicField(this, "fields", this.config.intervalConfig.fields);
        __publicField(this, "precision", this.config.intervalConfig.precision);
      }
      getSQLType() {
        const fields = this.fields ? ` ${this.fields}` : "";
        const precision = this.precision ? `(${this.precision})` : "";
        return `interval${fields}${precision}`;
      }
    };
    __publicField(PgInterval, _a66, "PgInterval");
  }
});

// ../drizzle-orm/dist/pg-core/columns/json.js
function json(name2) {
  return new PgJsonBuilder(name2 ?? "");
}
var _a67, _b46, PgJsonBuilder, _a68, _b47, PgJson;
var init_json = __esm({
  "../drizzle-orm/dist/pg-core/columns/json.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgJsonBuilder = class extends (_b46 = PgColumnBuilder, _a67 = entityKind, _b46) {
      constructor(name2) {
        super(name2, "json", "PgJson");
      }
      /** @internal */
      build(table6) {
        return new PgJson(table6, this.config);
      }
    };
    __publicField(PgJsonBuilder, _a67, "PgJsonBuilder");
    PgJson = class extends (_b47 = PgColumn, _a68 = entityKind, _b47) {
      constructor(table6, config) {
        super(table6, config);
      }
      getSQLType() {
        return "json";
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          try {
            return JSON.parse(value);
          } catch {
            return value;
          }
        }
        return value;
      }
    };
    __publicField(PgJson, _a68, "PgJson");
  }
});

// ../drizzle-orm/dist/pg-core/columns/jsonb.js
function jsonb(name2) {
  return new PgJsonbBuilder(name2 ?? "");
}
var _a69, _b48, PgJsonbBuilder, _a70, _b49, PgJsonb;
var init_jsonb = __esm({
  "../drizzle-orm/dist/pg-core/columns/jsonb.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgJsonbBuilder = class extends (_b48 = PgColumnBuilder, _a69 = entityKind, _b48) {
      constructor(name2) {
        super(name2, "json", "PgJsonb");
      }
      /** @internal */
      build(table6) {
        return new PgJsonb(table6, this.config);
      }
    };
    __publicField(PgJsonbBuilder, _a69, "PgJsonbBuilder");
    PgJsonb = class extends (_b49 = PgColumn, _a70 = entityKind, _b49) {
      constructor(table6, config) {
        super(table6, config);
      }
      getSQLType() {
        return "jsonb";
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          try {
            return JSON.parse(value);
          } catch {
            return value;
          }
        }
        return value;
      }
    };
    __publicField(PgJsonb, _a70, "PgJsonb");
  }
});

// ../drizzle-orm/dist/pg-core/columns/line.js
function line(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (!config?.mode || config.mode === "tuple") {
    return new PgLineBuilder(name2);
  }
  return new PgLineABCBuilder(name2);
}
var _a71, _b50, PgLineBuilder, _a72, _b51, PgLineTuple, _a73, _b52, PgLineABCBuilder, _a74, _b53, PgLineABC;
var init_line = __esm({
  "../drizzle-orm/dist/pg-core/columns/line.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgLineBuilder = class extends (_b50 = PgColumnBuilder, _a71 = entityKind, _b50) {
      constructor(name2) {
        super(name2, "array", "PgLine");
      }
      /** @internal */
      build(table6) {
        return new PgLineTuple(
          table6,
          this.config
        );
      }
    };
    __publicField(PgLineBuilder, _a71, "PgLineBuilder");
    PgLineTuple = class extends (_b51 = PgColumn, _a72 = entityKind, _b51) {
      getSQLType() {
        return "line";
      }
      mapFromDriverValue(value) {
        const [a, b, c] = value.slice(1, -1).split(",");
        return [Number.parseFloat(a), Number.parseFloat(b), Number.parseFloat(c)];
      }
      mapToDriverValue(value) {
        return `{${value[0]},${value[1]},${value[2]}}`;
      }
    };
    __publicField(PgLineTuple, _a72, "PgLine");
    PgLineABCBuilder = class extends (_b52 = PgColumnBuilder, _a73 = entityKind, _b52) {
      constructor(name2) {
        super(name2, "json", "PgLineABC");
      }
      /** @internal */
      build(table6) {
        return new PgLineABC(
          table6,
          this.config
        );
      }
    };
    __publicField(PgLineABCBuilder, _a73, "PgLineABCBuilder");
    PgLineABC = class extends (_b53 = PgColumn, _a74 = entityKind, _b53) {
      getSQLType() {
        return "line";
      }
      mapFromDriverValue(value) {
        const [a, b, c] = value.slice(1, -1).split(",");
        return { a: Number.parseFloat(a), b: Number.parseFloat(b), c: Number.parseFloat(c) };
      }
      mapToDriverValue(value) {
        return `{${value.a},${value.b},${value.c}}`;
      }
    };
    __publicField(PgLineABC, _a74, "PgLineABC");
  }
});

// ../drizzle-orm/dist/pg-core/columns/macaddr.js
function macaddr(name2) {
  return new PgMacaddrBuilder(name2 ?? "");
}
var _a75, _b54, PgMacaddrBuilder, _a76, _b55, PgMacaddr;
var init_macaddr = __esm({
  "../drizzle-orm/dist/pg-core/columns/macaddr.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgMacaddrBuilder = class extends (_b54 = PgColumnBuilder, _a75 = entityKind, _b54) {
      constructor(name2) {
        super(name2, "string", "PgMacaddr");
      }
      /** @internal */
      build(table6) {
        return new PgMacaddr(table6, this.config);
      }
    };
    __publicField(PgMacaddrBuilder, _a75, "PgMacaddrBuilder");
    PgMacaddr = class extends (_b55 = PgColumn, _a76 = entityKind, _b55) {
      getSQLType() {
        return "macaddr";
      }
    };
    __publicField(PgMacaddr, _a76, "PgMacaddr");
  }
});

// ../drizzle-orm/dist/pg-core/columns/macaddr8.js
function macaddr8(name2) {
  return new PgMacaddr8Builder(name2 ?? "");
}
var _a77, _b56, PgMacaddr8Builder, _a78, _b57, PgMacaddr8;
var init_macaddr8 = __esm({
  "../drizzle-orm/dist/pg-core/columns/macaddr8.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgMacaddr8Builder = class extends (_b56 = PgColumnBuilder, _a77 = entityKind, _b56) {
      constructor(name2) {
        super(name2, "string", "PgMacaddr8");
      }
      /** @internal */
      build(table6) {
        return new PgMacaddr8(table6, this.config);
      }
    };
    __publicField(PgMacaddr8Builder, _a77, "PgMacaddr8Builder");
    PgMacaddr8 = class extends (_b57 = PgColumn, _a78 = entityKind, _b57) {
      getSQLType() {
        return "macaddr8";
      }
    };
    __publicField(PgMacaddr8, _a78, "PgMacaddr8");
  }
});

// ../drizzle-orm/dist/pg-core/columns/numeric.js
function numeric(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  const mode = config?.mode;
  return mode === "number" ? new PgNumericNumberBuilder(name2, config?.precision, config?.scale) : mode === "bigint" ? new PgNumericBigIntBuilder(name2, config?.precision, config?.scale) : new PgNumericBuilder(name2, config?.precision, config?.scale);
}
var _a79, _b58, PgNumericBuilder, _a80, _b59, PgNumeric, _a81, _b60, PgNumericNumberBuilder, _a82, _b61, PgNumericNumber, _a83, _b62, PgNumericBigIntBuilder, _a84, _b63, PgNumericBigInt;
var init_numeric = __esm({
  "../drizzle-orm/dist/pg-core/columns/numeric.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgNumericBuilder = class extends (_b58 = PgColumnBuilder, _a79 = entityKind, _b58) {
      constructor(name2, precision, scale) {
        super(name2, "string", "PgNumeric");
        this.config.precision = precision;
        this.config.scale = scale;
      }
      /** @internal */
      build(table6) {
        return new PgNumeric(table6, this.config);
      }
    };
    __publicField(PgNumericBuilder, _a79, "PgNumericBuilder");
    PgNumeric = class extends (_b59 = PgColumn, _a80 = entityKind, _b59) {
      constructor(table6, config) {
        super(table6, config);
        __publicField(this, "precision");
        __publicField(this, "scale");
        this.precision = config.precision;
        this.scale = config.scale;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") return value;
        return String(value);
      }
      getSQLType() {
        if (this.precision !== void 0 && this.scale !== void 0) {
          return `numeric(${this.precision}, ${this.scale})`;
        } else if (this.precision === void 0) {
          return "numeric";
        } else {
          return `numeric(${this.precision})`;
        }
      }
    };
    __publicField(PgNumeric, _a80, "PgNumeric");
    PgNumericNumberBuilder = class extends (_b60 = PgColumnBuilder, _a81 = entityKind, _b60) {
      constructor(name2, precision, scale) {
        super(name2, "number", "PgNumericNumber");
        this.config.precision = precision;
        this.config.scale = scale;
      }
      /** @internal */
      build(table6) {
        return new PgNumericNumber(
          table6,
          this.config
        );
      }
    };
    __publicField(PgNumericNumberBuilder, _a81, "PgNumericNumberBuilder");
    PgNumericNumber = class extends (_b61 = PgColumn, _a82 = entityKind, _b61) {
      constructor(table6, config) {
        super(table6, config);
        __publicField(this, "precision");
        __publicField(this, "scale");
        __publicField(this, "mapToDriverValue", String);
        this.precision = config.precision;
        this.scale = config.scale;
      }
      mapFromDriverValue(value) {
        if (typeof value === "number") return value;
        return Number(value);
      }
      getSQLType() {
        if (this.precision !== void 0 && this.scale !== void 0) {
          return `numeric(${this.precision}, ${this.scale})`;
        } else if (this.precision === void 0) {
          return "numeric";
        } else {
          return `numeric(${this.precision})`;
        }
      }
    };
    __publicField(PgNumericNumber, _a82, "PgNumericNumber");
    PgNumericBigIntBuilder = class extends (_b62 = PgColumnBuilder, _a83 = entityKind, _b62) {
      constructor(name2, precision, scale) {
        super(name2, "bigint", "PgNumericBigInt");
        this.config.precision = precision;
        this.config.scale = scale;
      }
      /** @internal */
      build(table6) {
        return new PgNumericBigInt(
          table6,
          this.config
        );
      }
    };
    __publicField(PgNumericBigIntBuilder, _a83, "PgNumericBigIntBuilder");
    PgNumericBigInt = class extends (_b63 = PgColumn, _a84 = entityKind, _b63) {
      constructor(table6, config) {
        super(table6, config);
        __publicField(this, "precision");
        __publicField(this, "scale");
        __publicField(this, "mapFromDriverValue", BigInt);
        __publicField(this, "mapToDriverValue", String);
        this.precision = config.precision;
        this.scale = config.scale;
      }
      getSQLType() {
        if (this.precision !== void 0 && this.scale !== void 0) {
          return `numeric(${this.precision}, ${this.scale})`;
        } else if (this.precision === void 0) {
          return "numeric";
        } else {
          return `numeric(${this.precision})`;
        }
      }
    };
    __publicField(PgNumericBigInt, _a84, "PgNumericBigInt");
  }
});

// ../drizzle-orm/dist/pg-core/columns/point.js
function point(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (!config?.mode || config.mode === "tuple") {
    return new PgPointTupleBuilder(name2);
  }
  return new PgPointObjectBuilder(name2);
}
var _a85, _b64, PgPointTupleBuilder, _a86, _b65, PgPointTuple, _a87, _b66, PgPointObjectBuilder, _a88, _b67, PgPointObject;
var init_point = __esm({
  "../drizzle-orm/dist/pg-core/columns/point.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgPointTupleBuilder = class extends (_b64 = PgColumnBuilder, _a85 = entityKind, _b64) {
      constructor(name2) {
        super(name2, "array", "PgPointTuple");
      }
      /** @internal */
      build(table6) {
        return new PgPointTuple(
          table6,
          this.config
        );
      }
    };
    __publicField(PgPointTupleBuilder, _a85, "PgPointTupleBuilder");
    PgPointTuple = class extends (_b65 = PgColumn, _a86 = entityKind, _b65) {
      getSQLType() {
        return "point";
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          const [x, y] = value.slice(1, -1).split(",");
          return [Number.parseFloat(x), Number.parseFloat(y)];
        }
        return [value.x, value.y];
      }
      mapToDriverValue(value) {
        return `(${value[0]},${value[1]})`;
      }
    };
    __publicField(PgPointTuple, _a86, "PgPointTuple");
    PgPointObjectBuilder = class extends (_b66 = PgColumnBuilder, _a87 = entityKind, _b66) {
      constructor(name2) {
        super(name2, "json", "PgPointObject");
      }
      /** @internal */
      build(table6) {
        return new PgPointObject(
          table6,
          this.config
        );
      }
    };
    __publicField(PgPointObjectBuilder, _a87, "PgPointObjectBuilder");
    PgPointObject = class extends (_b67 = PgColumn, _a88 = entityKind, _b67) {
      getSQLType() {
        return "point";
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          const [x, y] = value.slice(1, -1).split(",");
          return { x: Number.parseFloat(x), y: Number.parseFloat(y) };
        }
        return value;
      }
      mapToDriverValue(value) {
        return `(${value.x},${value.y})`;
      }
    };
    __publicField(PgPointObject, _a88, "PgPointObject");
  }
});

// ../drizzle-orm/dist/pg-core/columns/postgis_extension/utils.js
function hexToBytes(hex) {
  const bytes = [];
  for (let c = 0; c < hex.length; c += 2) {
    bytes.push(Number.parseInt(hex.slice(c, c + 2), 16));
  }
  return new Uint8Array(bytes);
}
function bytesToFloat64(bytes, offset) {
  const buffer = new ArrayBuffer(8);
  const view5 = new DataView(buffer);
  for (let i = 0; i < 8; i++) {
    view5.setUint8(i, bytes[offset + i]);
  }
  return view5.getFloat64(0, true);
}
function parseEWKB(hex) {
  const bytes = hexToBytes(hex);
  let offset = 0;
  const byteOrder = bytes[offset];
  offset += 1;
  const view5 = new DataView(bytes.buffer);
  const geomType = view5.getUint32(offset, byteOrder === 1);
  offset += 4;
  let _srid;
  if (geomType & 536870912) {
    _srid = view5.getUint32(offset, byteOrder === 1);
    offset += 4;
  }
  if ((geomType & 65535) === 1) {
    const x = bytesToFloat64(bytes, offset);
    offset += 8;
    const y = bytesToFloat64(bytes, offset);
    offset += 8;
    return [x, y];
  }
  throw new Error("Unsupported geometry type");
}
var init_utils3 = __esm({
  "../drizzle-orm/dist/pg-core/columns/postgis_extension/utils.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/pg-core/columns/postgis_extension/geometry.js
function geometry(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (!config?.mode || config.mode === "tuple") {
    return new PgGeometryBuilder(name2);
  }
  return new PgGeometryObjectBuilder(name2);
}
var _a89, _b68, PgGeometryBuilder, _a90, _b69, PgGeometry, _a91, _b70, PgGeometryObjectBuilder, _a92, _b71, PgGeometryObject;
var init_geometry = __esm({
  "../drizzle-orm/dist/pg-core/columns/postgis_extension/geometry.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    init_utils3();
    PgGeometryBuilder = class extends (_b68 = PgColumnBuilder, _a89 = entityKind, _b68) {
      constructor(name2) {
        super(name2, "array", "PgGeometry");
      }
      /** @internal */
      build(table6) {
        return new PgGeometry(
          table6,
          this.config
        );
      }
    };
    __publicField(PgGeometryBuilder, _a89, "PgGeometryBuilder");
    PgGeometry = class extends (_b69 = PgColumn, _a90 = entityKind, _b69) {
      getSQLType() {
        return "geometry(point)";
      }
      mapFromDriverValue(value) {
        return parseEWKB(value);
      }
      mapToDriverValue(value) {
        return `point(${value[0]} ${value[1]})`;
      }
    };
    __publicField(PgGeometry, _a90, "PgGeometry");
    PgGeometryObjectBuilder = class extends (_b70 = PgColumnBuilder, _a91 = entityKind, _b70) {
      constructor(name2) {
        super(name2, "json", "PgGeometryObject");
      }
      /** @internal */
      build(table6) {
        return new PgGeometryObject(
          table6,
          this.config
        );
      }
    };
    __publicField(PgGeometryObjectBuilder, _a91, "PgGeometryObjectBuilder");
    PgGeometryObject = class extends (_b71 = PgColumn, _a92 = entityKind, _b71) {
      getSQLType() {
        return "geometry(point)";
      }
      mapFromDriverValue(value) {
        const parsed = parseEWKB(value);
        return { x: parsed[0], y: parsed[1] };
      }
      mapToDriverValue(value) {
        return `point(${value.x} ${value.y})`;
      }
    };
    __publicField(PgGeometryObject, _a92, "PgGeometryObject");
  }
});

// ../drizzle-orm/dist/pg-core/columns/real.js
function real(name2) {
  return new PgRealBuilder(name2 ?? "");
}
var _a93, _b72, PgRealBuilder, _a94, _b73, PgReal;
var init_real = __esm({
  "../drizzle-orm/dist/pg-core/columns/real.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgRealBuilder = class extends (_b72 = PgColumnBuilder, _a93 = entityKind, _b72) {
      constructor(name2, length) {
        super(name2, "number", "PgReal");
        this.config.length = length;
      }
      /** @internal */
      build(table6) {
        return new PgReal(table6, this.config);
      }
    };
    __publicField(PgRealBuilder, _a93, "PgRealBuilder");
    PgReal = class extends (_b73 = PgColumn, _a94 = entityKind, _b73) {
      constructor(table6, config) {
        super(table6, config);
        __publicField(this, "mapFromDriverValue", (value) => {
          if (typeof value === "string") {
            return Number.parseFloat(value);
          }
          return value;
        });
      }
      getSQLType() {
        return "real";
      }
    };
    __publicField(PgReal, _a94, "PgReal");
  }
});

// ../drizzle-orm/dist/pg-core/columns/serial.js
function serial(name2) {
  return new PgSerialBuilder(name2 ?? "");
}
var _a95, _b74, PgSerialBuilder, _a96, _b75, PgSerial;
var init_serial = __esm({
  "../drizzle-orm/dist/pg-core/columns/serial.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgSerialBuilder = class extends (_b74 = PgColumnBuilder, _a95 = entityKind, _b74) {
      constructor(name2) {
        super(name2, "number", "PgSerial");
        this.config.hasDefault = true;
        this.config.notNull = true;
      }
      /** @internal */
      build(table6) {
        return new PgSerial(table6, this.config);
      }
    };
    __publicField(PgSerialBuilder, _a95, "PgSerialBuilder");
    PgSerial = class extends (_b75 = PgColumn, _a96 = entityKind, _b75) {
      getSQLType() {
        return "serial";
      }
    };
    __publicField(PgSerial, _a96, "PgSerial");
  }
});

// ../drizzle-orm/dist/pg-core/columns/smallint.js
function smallint(name2) {
  return new PgSmallIntBuilder(name2 ?? "");
}
var _a97, _b76, PgSmallIntBuilder, _a98, _b77, PgSmallInt;
var init_smallint = __esm({
  "../drizzle-orm/dist/pg-core/columns/smallint.js"() {
    "use strict";
    init_entity();
    init_common2();
    init_int_common();
    PgSmallIntBuilder = class extends (_b76 = PgIntColumnBaseBuilder, _a97 = entityKind, _b76) {
      constructor(name2) {
        super(name2, "number", "PgSmallInt");
      }
      /** @internal */
      build(table6) {
        return new PgSmallInt(table6, this.config);
      }
    };
    __publicField(PgSmallIntBuilder, _a97, "PgSmallIntBuilder");
    PgSmallInt = class extends (_b77 = PgColumn, _a98 = entityKind, _b77) {
      constructor() {
        super(...arguments);
        __publicField(this, "mapFromDriverValue", (value) => {
          if (typeof value === "string") {
            return Number(value);
          }
          return value;
        });
      }
      getSQLType() {
        return "smallint";
      }
    };
    __publicField(PgSmallInt, _a98, "PgSmallInt");
  }
});

// ../drizzle-orm/dist/pg-core/columns/smallserial.js
function smallserial(name2) {
  return new PgSmallSerialBuilder(name2 ?? "");
}
var _a99, _b78, PgSmallSerialBuilder, _a100, _b79, PgSmallSerial;
var init_smallserial = __esm({
  "../drizzle-orm/dist/pg-core/columns/smallserial.js"() {
    "use strict";
    init_entity();
    init_common2();
    PgSmallSerialBuilder = class extends (_b78 = PgColumnBuilder, _a99 = entityKind, _b78) {
      constructor(name2) {
        super(name2, "number", "PgSmallSerial");
        this.config.hasDefault = true;
        this.config.notNull = true;
      }
      /** @internal */
      build(table6) {
        return new PgSmallSerial(
          table6,
          this.config
        );
      }
    };
    __publicField(PgSmallSerialBuilder, _a99, "PgSmallSerialBuilder");
    PgSmallSerial = class extends (_b79 = PgColumn, _a100 = entityKind, _b79) {
      getSQLType() {
        return "smallserial";
      }
    };
    __publicField(PgSmallSerial, _a100, "PgSmallSerial");
  }
});

// ../drizzle-orm/dist/pg-core/columns/text.js
function text(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgTextBuilder(name2, config);
}
var _a101, _b80, PgTextBuilder, _a102, _b81, PgText;
var init_text = __esm({
  "../drizzle-orm/dist/pg-core/columns/text.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgTextBuilder = class extends (_b80 = PgColumnBuilder, _a101 = entityKind, _b80) {
      constructor(name2, config) {
        super(name2, "string", "PgText");
        this.config.enumValues = config.enum;
      }
      /** @internal */
      build(table6) {
        return new PgText(table6, this.config);
      }
    };
    __publicField(PgTextBuilder, _a101, "PgTextBuilder");
    PgText = class extends (_b81 = PgColumn, _a102 = entityKind, _b81) {
      constructor() {
        super(...arguments);
        __publicField(this, "enumValues", this.config.enumValues);
      }
      getSQLType() {
        return "text";
      }
    };
    __publicField(PgText, _a102, "PgText");
  }
});

// ../drizzle-orm/dist/pg-core/columns/time.js
function time(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgTimeBuilder(name2, config.withTimezone ?? false, config.precision);
}
var _a103, _b82, PgTimeBuilder, _a104, _b83, PgTime;
var init_time = __esm({
  "../drizzle-orm/dist/pg-core/columns/time.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    init_date_common();
    PgTimeBuilder = class extends (_b82 = PgDateColumnBaseBuilder, _a103 = entityKind, _b82) {
      constructor(name2, withTimezone, precision) {
        super(name2, "string", "PgTime");
        this.withTimezone = withTimezone;
        this.precision = precision;
        this.config.withTimezone = withTimezone;
        this.config.precision = precision;
      }
      /** @internal */
      build(table6) {
        return new PgTime(table6, this.config);
      }
    };
    __publicField(PgTimeBuilder, _a103, "PgTimeBuilder");
    PgTime = class extends (_b83 = PgColumn, _a104 = entityKind, _b83) {
      constructor(table6, config) {
        super(table6, config);
        __publicField(this, "withTimezone");
        __publicField(this, "precision");
        this.withTimezone = config.withTimezone;
        this.precision = config.precision;
      }
      getSQLType() {
        const precision = this.precision === void 0 ? "" : `(${this.precision})`;
        return `time${precision}${this.withTimezone ? " with time zone" : ""}`;
      }
    };
    __publicField(PgTime, _a104, "PgTime");
  }
});

// ../drizzle-orm/dist/pg-core/columns/timestamp.js
function timestamp(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config?.mode === "string") {
    return new PgTimestampStringBuilder(name2, config.withTimezone ?? false, config.precision);
  }
  return new PgTimestampBuilder(name2, config?.withTimezone ?? false, config?.precision);
}
var _a105, _b84, PgTimestampBuilder, _a106, _b85, PgTimestamp, _a107, _b86, PgTimestampStringBuilder, _a108, _b87, PgTimestampString;
var init_timestamp = __esm({
  "../drizzle-orm/dist/pg-core/columns/timestamp.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    init_date_common();
    PgTimestampBuilder = class extends (_b84 = PgDateColumnBaseBuilder, _a105 = entityKind, _b84) {
      constructor(name2, withTimezone, precision) {
        super(name2, "date", "PgTimestamp");
        this.config.withTimezone = withTimezone;
        this.config.precision = precision;
      }
      /** @internal */
      build(table6) {
        return new PgTimestamp(table6, this.config);
      }
    };
    __publicField(PgTimestampBuilder, _a105, "PgTimestampBuilder");
    PgTimestamp = class extends (_b85 = PgColumn, _a106 = entityKind, _b85) {
      constructor(table6, config) {
        super(table6, config);
        __publicField(this, "withTimezone");
        __publicField(this, "precision");
        __publicField(this, "mapFromDriverValue", (value) => {
          return new Date(this.withTimezone ? value : value + "+0000");
        });
        __publicField(this, "mapToDriverValue", (value) => {
          return value.toISOString();
        });
        this.withTimezone = config.withTimezone;
        this.precision = config.precision;
      }
      getSQLType() {
        const precision = this.precision === void 0 ? "" : ` (${this.precision})`;
        return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`;
      }
    };
    __publicField(PgTimestamp, _a106, "PgTimestamp");
    PgTimestampStringBuilder = class extends (_b86 = PgDateColumnBaseBuilder, _a107 = entityKind, _b86) {
      constructor(name2, withTimezone, precision) {
        super(name2, "string", "PgTimestampString");
        this.config.withTimezone = withTimezone;
        this.config.precision = precision;
      }
      /** @internal */
      build(table6) {
        return new PgTimestampString(
          table6,
          this.config
        );
      }
    };
    __publicField(PgTimestampStringBuilder, _a107, "PgTimestampStringBuilder");
    PgTimestampString = class extends (_b87 = PgColumn, _a108 = entityKind, _b87) {
      constructor(table6, config) {
        super(table6, config);
        __publicField(this, "withTimezone");
        __publicField(this, "precision");
        this.withTimezone = config.withTimezone;
        this.precision = config.precision;
      }
      getSQLType() {
        const precision = this.precision === void 0 ? "" : `(${this.precision})`;
        return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`;
      }
    };
    __publicField(PgTimestampString, _a108, "PgTimestampString");
  }
});

// ../drizzle-orm/dist/pg-core/columns/uuid.js
function uuid(name2) {
  return new PgUUIDBuilder(name2 ?? "");
}
var _a109, _b88, PgUUIDBuilder, _a110, _b89, PgUUID;
var init_uuid = __esm({
  "../drizzle-orm/dist/pg-core/columns/uuid.js"() {
    "use strict";
    init_entity();
    init_sql();
    init_common2();
    PgUUIDBuilder = class extends (_b88 = PgColumnBuilder, _a109 = entityKind, _b88) {
      constructor(name2) {
        super(name2, "string", "PgUUID");
      }
      /**
       * Adds `default gen_random_uuid()` to the column definition.
       */
      defaultRandom() {
        return this.default(sql`gen_random_uuid()`);
      }
      /** @internal */
      build(table6) {
        return new PgUUID(table6, this.config);
      }
    };
    __publicField(PgUUIDBuilder, _a109, "PgUUIDBuilder");
    PgUUID = class extends (_b89 = PgColumn, _a110 = entityKind, _b89) {
      getSQLType() {
        return "uuid";
      }
    };
    __publicField(PgUUID, _a110, "PgUUID");
  }
});

// ../drizzle-orm/dist/pg-core/columns/varchar.js
function varchar(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgVarcharBuilder(name2, config);
}
var _a111, _b90, PgVarcharBuilder, _a112, _b91, PgVarchar;
var init_varchar = __esm({
  "../drizzle-orm/dist/pg-core/columns/varchar.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgVarcharBuilder = class extends (_b90 = PgColumnBuilder, _a111 = entityKind, _b90) {
      constructor(name2, config) {
        super(name2, "string", "PgVarchar");
        this.config.length = config.length;
        this.config.enumValues = config.enum;
      }
      /** @internal */
      build(table6) {
        return new PgVarchar(
          table6,
          this.config
        );
      }
    };
    __publicField(PgVarcharBuilder, _a111, "PgVarcharBuilder");
    PgVarchar = class extends (_b91 = PgColumn, _a112 = entityKind, _b91) {
      constructor() {
        super(...arguments);
        __publicField(this, "length", this.config.length);
        __publicField(this, "enumValues", this.config.enumValues);
      }
      getSQLType() {
        return this.length === void 0 ? `varchar` : `varchar(${this.length})`;
      }
    };
    __publicField(PgVarchar, _a112, "PgVarchar");
  }
});

// ../drizzle-orm/dist/pg-core/columns/vector_extension/bit.js
function bit(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgBinaryVectorBuilder(name2, config);
}
var _a113, _b92, PgBinaryVectorBuilder, _a114, _b93, PgBinaryVector;
var init_bit = __esm({
  "../drizzle-orm/dist/pg-core/columns/vector_extension/bit.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgBinaryVectorBuilder = class extends (_b92 = PgColumnBuilder, _a113 = entityKind, _b92) {
      constructor(name2, config) {
        super(name2, "string", "PgBinaryVector");
        this.config.dimensions = config.dimensions;
      }
      /** @internal */
      build(table6) {
        return new PgBinaryVector(
          table6,
          this.config
        );
      }
    };
    __publicField(PgBinaryVectorBuilder, _a113, "PgBinaryVectorBuilder");
    PgBinaryVector = class extends (_b93 = PgColumn, _a114 = entityKind, _b93) {
      constructor() {
        super(...arguments);
        __publicField(this, "dimensions", this.config.dimensions);
      }
      getSQLType() {
        return `bit(${this.dimensions})`;
      }
    };
    __publicField(PgBinaryVector, _a114, "PgBinaryVector");
  }
});

// ../drizzle-orm/dist/pg-core/columns/vector_extension/halfvec.js
function halfvec(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgHalfVectorBuilder(name2, config);
}
var _a115, _b94, PgHalfVectorBuilder, _a116, _b95, PgHalfVector;
var init_halfvec = __esm({
  "../drizzle-orm/dist/pg-core/columns/vector_extension/halfvec.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgHalfVectorBuilder = class extends (_b94 = PgColumnBuilder, _a115 = entityKind, _b94) {
      constructor(name2, config) {
        super(name2, "array", "PgHalfVector");
        this.config.dimensions = config.dimensions;
      }
      /** @internal */
      build(table6) {
        return new PgHalfVector(
          table6,
          this.config
        );
      }
    };
    __publicField(PgHalfVectorBuilder, _a115, "PgHalfVectorBuilder");
    PgHalfVector = class extends (_b95 = PgColumn, _a116 = entityKind, _b95) {
      constructor() {
        super(...arguments);
        __publicField(this, "dimensions", this.config.dimensions);
      }
      getSQLType() {
        return `halfvec(${this.dimensions})`;
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
      mapFromDriverValue(value) {
        return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v));
      }
    };
    __publicField(PgHalfVector, _a116, "PgHalfVector");
  }
});

// ../drizzle-orm/dist/pg-core/columns/vector_extension/sparsevec.js
function sparsevec(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgSparseVectorBuilder(name2, config);
}
var _a117, _b96, PgSparseVectorBuilder, _a118, _b97, PgSparseVector;
var init_sparsevec = __esm({
  "../drizzle-orm/dist/pg-core/columns/vector_extension/sparsevec.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgSparseVectorBuilder = class extends (_b96 = PgColumnBuilder, _a117 = entityKind, _b96) {
      constructor(name2, config) {
        super(name2, "string", "PgSparseVector");
        this.config.dimensions = config.dimensions;
      }
      /** @internal */
      build(table6) {
        return new PgSparseVector(
          table6,
          this.config
        );
      }
    };
    __publicField(PgSparseVectorBuilder, _a117, "PgSparseVectorBuilder");
    PgSparseVector = class extends (_b97 = PgColumn, _a118 = entityKind, _b97) {
      constructor() {
        super(...arguments);
        __publicField(this, "dimensions", this.config.dimensions);
      }
      getSQLType() {
        return `sparsevec(${this.dimensions})`;
      }
    };
    __publicField(PgSparseVector, _a118, "PgSparseVector");
  }
});

// ../drizzle-orm/dist/pg-core/columns/vector_extension/vector.js
function vector(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new PgVectorBuilder(name2, config);
}
var _a119, _b98, PgVectorBuilder, _a120, _b99, PgVector;
var init_vector = __esm({
  "../drizzle-orm/dist/pg-core/columns/vector_extension/vector.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common2();
    PgVectorBuilder = class extends (_b98 = PgColumnBuilder, _a119 = entityKind, _b98) {
      constructor(name2, config) {
        super(name2, "array", "PgVector");
        this.config.dimensions = config.dimensions;
      }
      /** @internal */
      build(table6) {
        return new PgVector(
          table6,
          this.config
        );
      }
    };
    __publicField(PgVectorBuilder, _a119, "PgVectorBuilder");
    PgVector = class extends (_b99 = PgColumn, _a120 = entityKind, _b99) {
      constructor() {
        super(...arguments);
        __publicField(this, "dimensions", this.config.dimensions);
      }
      getSQLType() {
        return `vector(${this.dimensions})`;
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
      mapFromDriverValue(value) {
        return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v));
      }
    };
    __publicField(PgVector, _a120, "PgVector");
  }
});

// ../drizzle-orm/dist/pg-core/columns/all.js
function getPgColumnBuilders() {
  return {
    bigint,
    bigserial,
    boolean,
    char,
    cidr,
    customType,
    date,
    doublePrecision,
    inet,
    integer,
    interval,
    json,
    jsonb,
    line,
    macaddr,
    macaddr8,
    numeric,
    point,
    geometry,
    real,
    serial,
    smallint,
    smallserial,
    text,
    time,
    timestamp,
    uuid,
    varchar,
    bit,
    halfvec,
    sparsevec,
    vector
  };
}
var init_all = __esm({
  "../drizzle-orm/dist/pg-core/columns/all.js"() {
    "use strict";
    init_bigint();
    init_bigserial();
    init_boolean();
    init_char();
    init_cidr();
    init_custom();
    init_date();
    init_double_precision();
    init_inet();
    init_integer();
    init_interval();
    init_json();
    init_jsonb();
    init_line();
    init_macaddr();
    init_macaddr8();
    init_numeric();
    init_point();
    init_geometry();
    init_real();
    init_serial();
    init_smallint();
    init_smallserial();
    init_text();
    init_time();
    init_timestamp();
    init_uuid();
    init_varchar();
    init_bit();
    init_halfvec();
    init_sparsevec();
    init_vector();
  }
});

// ../drizzle-orm/dist/pg-core/table.js
function pgTableWithSchema(name2, columns, extraConfig, schema5, baseName = name2) {
  const rawTable = new PgTable(name2, schema5, baseName);
  const parsedColumns = typeof columns === "function" ? columns(getPgColumnBuilders()) : columns;
  const builtColumns = Object.fromEntries(
    Object.entries(parsedColumns).map(([name22, colBuilderBase]) => {
      const colBuilder = colBuilderBase;
      colBuilder.setName(name22);
      const column6 = colBuilder.build(rawTable);
      rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column6, rawTable));
      return [name22, column6];
    })
  );
  const builtColumnsForExtraConfig = Object.fromEntries(
    Object.entries(parsedColumns).map(([name22, colBuilderBase]) => {
      const colBuilder = colBuilderBase;
      colBuilder.setName(name22);
      const column6 = colBuilder.buildExtraConfigColumn(rawTable);
      return [name22, column6];
    })
  );
  const table6 = Object.assign(rawTable, builtColumns);
  table6[Table2.Symbol.Columns] = builtColumns;
  table6[Table2.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig;
  if (extraConfig) {
    table6[PgTable.Symbol.ExtraConfigBuilder] = extraConfig;
  }
  return Object.assign(table6, {
    enableRLS: () => {
      table6[PgTable.Symbol.EnableRLS] = true;
      return table6;
    }
  });
}
var InlineForeignKeys, EnableRLS, _a121, _b100, _c3, _d2, _e2, _f2, PgTable, pgTable;
var init_table2 = __esm({
  "../drizzle-orm/dist/pg-core/table.js"() {
    "use strict";
    init_entity();
    init_table();
    init_all();
    InlineForeignKeys = Symbol.for("drizzle:PgInlineForeignKeys");
    EnableRLS = Symbol.for("drizzle:EnableRLS");
    PgTable = class extends (_f2 = Table2, _e2 = entityKind, _d2 = InlineForeignKeys, _c3 = EnableRLS, _b100 = Table2.Symbol.ExtraConfigBuilder, _a121 = Table2.Symbol.ExtraConfigColumns, _f2) {
      constructor() {
        super(...arguments);
        /**@internal */
        __publicField(this, _d2, []);
        /** @internal */
        __publicField(this, _c3, false);
        /** @internal */
        __publicField(this, _b100);
        /** @internal */
        __publicField(this, _a121, {});
      }
    };
    __publicField(PgTable, _e2, "PgTable");
    /** @internal */
    __publicField(PgTable, "Symbol", Object.assign({}, Table2.Symbol, {
      InlineForeignKeys,
      EnableRLS
    }));
    pgTable = (name2, columns, extraConfig) => {
      return pgTableWithSchema(name2, columns, extraConfig, void 0);
    };
  }
});

// ../drizzle-orm/dist/pg-core/primary-keys.js
var _a122, PrimaryKeyBuilder, _a123, PrimaryKey;
var init_primary_keys = __esm({
  "../drizzle-orm/dist/pg-core/primary-keys.js"() {
    "use strict";
    init_entity();
    init_table2();
    _a122 = entityKind;
    PrimaryKeyBuilder = class {
      constructor(columns, name2) {
        /** @internal */
        __publicField(this, "columns");
        /** @internal */
        __publicField(this, "name");
        this.columns = columns;
        this.name = name2;
      }
      /** @internal */
      build(table6) {
        return new PrimaryKey(table6, this.columns, this.name);
      }
    };
    __publicField(PrimaryKeyBuilder, _a122, "PgPrimaryKeyBuilder");
    _a123 = entityKind;
    PrimaryKey = class {
      constructor(table6, columns, name2) {
        __publicField(this, "columns");
        __publicField(this, "name");
        this.table = table6;
        this.columns = columns;
        this.name = name2;
      }
      getName() {
        return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column6) => column6.name).join("_")}_pk`;
      }
    };
    __publicField(PrimaryKey, _a123, "PgPrimaryKey");
  }
});

// ../drizzle-orm/dist/sql/expressions/conditions.js
function bindIfParam(value, column6) {
  if (isDriverValueEncoder(column6) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column2) && !is(value, Table2) && !is(value, View3)) {
    return new Param(value, column6);
  }
  return value;
}
function and(...unfilteredConditions) {
  const conditions = unfilteredConditions.filter(
    (c) => c !== void 0
  );
  if (conditions.length === 0) {
    return void 0;
  }
  if (conditions.length === 1) {
    return new SQL(conditions);
  }
  return new SQL([
    new StringChunk("("),
    sql.join(conditions, new StringChunk(" and ")),
    new StringChunk(")")
  ]);
}
function or(...unfilteredConditions) {
  const conditions = unfilteredConditions.filter(
    (c) => c !== void 0
  );
  if (conditions.length === 0) {
    return void 0;
  }
  if (conditions.length === 1) {
    return new SQL(conditions);
  }
  return new SQL([
    new StringChunk("("),
    sql.join(conditions, new StringChunk(" or ")),
    new StringChunk(")")
  ]);
}
function not(condition) {
  return sql`not ${condition}`;
}
function inArray(column6, values) {
  if (Array.isArray(values)) {
    if (values.length === 0) {
      return sql`false`;
    }
    return sql`${column6} in ${values.map((v) => bindIfParam(v, column6))}`;
  }
  return sql`${column6} in ${bindIfParam(values, column6)}`;
}
function notInArray(column6, values) {
  if (Array.isArray(values)) {
    if (values.length === 0) {
      return sql`true`;
    }
    return sql`${column6} not in ${values.map((v) => bindIfParam(v, column6))}`;
  }
  return sql`${column6} not in ${bindIfParam(values, column6)}`;
}
function isNull(value) {
  return sql`${value} is null`;
}
function isNotNull(value) {
  return sql`${value} is not null`;
}
function exists(subquery) {
  return sql`exists ${subquery}`;
}
function notExists(subquery) {
  return sql`not exists ${subquery}`;
}
function between(column6, min2, max2) {
  return sql`${column6} between ${bindIfParam(min2, column6)} and ${bindIfParam(
    max2,
    column6
  )}`;
}
function notBetween(column6, min2, max2) {
  return sql`${column6} not between ${bindIfParam(
    min2,
    column6
  )} and ${bindIfParam(max2, column6)}`;
}
function like(column6, value) {
  return sql`${column6} like ${value}`;
}
function notLike(column6, value) {
  return sql`${column6} not like ${value}`;
}
function ilike(column6, value) {
  return sql`${column6} ilike ${value}`;
}
function notIlike(column6, value) {
  return sql`${column6} not ilike ${value}`;
}
function arrayContains(column6, values) {
  if (Array.isArray(values)) {
    if (values.length === 0) {
      throw new Error("arrayContains requires at least one value");
    }
    const array2 = sql`${bindIfParam(values, column6)}`;
    return sql`${column6} @> ${array2}`;
  }
  return sql`${column6} @> ${bindIfParam(values, column6)}`;
}
function arrayContained(column6, values) {
  if (Array.isArray(values)) {
    if (values.length === 0) {
      throw new Error("arrayContained requires at least one value");
    }
    const array2 = sql`${bindIfParam(values, column6)}`;
    return sql`${column6} <@ ${array2}`;
  }
  return sql`${column6} <@ ${bindIfParam(values, column6)}`;
}
function arrayOverlaps(column6, values) {
  if (Array.isArray(values)) {
    if (values.length === 0) {
      throw new Error("arrayOverlaps requires at least one value");
    }
    const array2 = sql`${bindIfParam(values, column6)}`;
    return sql`${column6} && ${array2}`;
  }
  return sql`${column6} && ${bindIfParam(values, column6)}`;
}
var eq, ne, gt, gte, lt, lte;
var init_conditions = __esm({
  "../drizzle-orm/dist/sql/expressions/conditions.js"() {
    "use strict";
    init_column();
    init_entity();
    init_table();
    init_sql();
    eq = (left, right) => {
      return sql`${left} = ${bindIfParam(right, left)}`;
    };
    ne = (left, right) => {
      return sql`${left} <> ${bindIfParam(right, left)}`;
    };
    gt = (left, right) => {
      return sql`${left} > ${bindIfParam(right, left)}`;
    };
    gte = (left, right) => {
      return sql`${left} >= ${bindIfParam(right, left)}`;
    };
    lt = (left, right) => {
      return sql`${left} < ${bindIfParam(right, left)}`;
    };
    lte = (left, right) => {
      return sql`${left} <= ${bindIfParam(right, left)}`;
    };
  }
});

// ../drizzle-orm/dist/sql/expressions/select.js
function asc(column6) {
  return sql`${column6} asc`;
}
function desc(column6) {
  return sql`${column6} desc`;
}
var init_select = __esm({
  "../drizzle-orm/dist/sql/expressions/select.js"() {
    "use strict";
    init_sql();
  }
});

// ../drizzle-orm/dist/sql/expressions/index.js
var init_expressions = __esm({
  "../drizzle-orm/dist/sql/expressions/index.js"() {
    "use strict";
    init_conditions();
    init_select();
  }
});

// ../drizzle-orm/dist/relations.js
function getOperators() {
  return {
    and,
    between,
    eq,
    exists,
    gt,
    gte,
    ilike,
    inArray,
    isNull,
    isNotNull,
    like,
    lt,
    lte,
    ne,
    not,
    notBetween,
    notExists,
    notLike,
    notIlike,
    notInArray,
    or,
    sql
  };
}
function getOrderByOperators() {
  return {
    sql,
    asc,
    desc
  };
}
function extractTablesRelationalConfig(schema5, configHelpers) {
  if (Object.keys(schema5).length === 1 && "default" in schema5 && !is(schema5["default"], Table2)) {
    schema5 = schema5["default"];
  }
  const tableNamesMap = {};
  const relationsBuffer = {};
  const tablesConfig = {};
  for (const [key, value] of Object.entries(schema5)) {
    if (is(value, Table2)) {
      const dbName = getTableUniqueName(value);
      const bufferedRelations = relationsBuffer[dbName];
      tableNamesMap[dbName] = key;
      tablesConfig[key] = {
        tsName: key,
        dbName: value[Table2.Symbol.Name],
        schema: value[Table2.Symbol.Schema],
        columns: value[Table2.Symbol.Columns],
        relations: bufferedRelations?.relations ?? {},
        primaryKey: bufferedRelations?.primaryKey ?? []
      };
      for (const column6 of Object.values(
        value[Table2.Symbol.Columns]
      )) {
        if (column6.primary) {
          tablesConfig[key].primaryKey.push(column6);
        }
      }
      const extraConfig = value[Table2.Symbol.ExtraConfigBuilder]?.(value[Table2.Symbol.ExtraConfigColumns]);
      if (extraConfig) {
        for (const configEntry of Object.values(extraConfig)) {
          if (is(configEntry, PrimaryKeyBuilder)) {
            tablesConfig[key].primaryKey.push(...configEntry.columns);
          }
        }
      }
    } else if (is(value, Relations)) {
      const dbName = getTableUniqueName(value.table);
      const tableName = tableNamesMap[dbName];
      const relations2 = value.config(
        configHelpers(value.table)
      );
      let primaryKey;
      for (const [relationName, relation] of Object.entries(relations2)) {
        if (tableName) {
          const tableConfig = tablesConfig[tableName];
          tableConfig.relations[relationName] = relation;
          if (primaryKey) {
            tableConfig.primaryKey.push(...primaryKey);
          }
        } else {
          if (!(dbName in relationsBuffer)) {
            relationsBuffer[dbName] = {
              relations: {},
              primaryKey
            };
          }
          relationsBuffer[dbName].relations[relationName] = relation;
        }
      }
    }
  }
  return { tables: tablesConfig, tableNamesMap };
}
function relations(table6, relations2) {
  return new Relations(
    table6,
    (helpers) => Object.fromEntries(
      Object.entries(relations2(helpers)).map(([key, value]) => [
        key,
        value.withFieldName(key)
      ])
    )
  );
}
function createOne(sourceTable) {
  return function one(table6, config) {
    return new One(
      sourceTable,
      table6,
      config,
      config?.fields.reduce((res, f) => res && f.notNull, true) ?? false
    );
  };
}
function createMany(sourceTable) {
  return function many(referencedTable, config) {
    return new Many(sourceTable, referencedTable, config);
  };
}
function normalizeRelation(schema5, tableNamesMap, relation) {
  if (is(relation, One) && relation.config) {
    return {
      fields: relation.config.fields,
      references: relation.config.references
    };
  }
  const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)];
  if (!referencedTableTsName) {
    throw new Error(
      `Table "${relation.referencedTable[Table2.Symbol.Name]}" not found in schema`
    );
  }
  const referencedTableConfig = schema5[referencedTableTsName];
  if (!referencedTableConfig) {
    throw new Error(`Table "${referencedTableTsName}" not found in schema`);
  }
  const sourceTable = relation.sourceTable;
  const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)];
  if (!sourceTableTsName) {
    throw new Error(
      `Table "${sourceTable[Table2.Symbol.Name]}" not found in schema`
    );
  }
  const reverseRelations = [];
  for (const referencedTableRelation of Object.values(
    referencedTableConfig.relations
  )) {
    if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) {
      reverseRelations.push(referencedTableRelation);
    }
  }
  if (reverseRelations.length > 1) {
    throw relation.relationName ? new Error(
      `There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"`
    ) : new Error(
      `There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table2.Symbol.Name]}". Please specify relation name`
    );
  }
  if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) {
    return {
      fields: reverseRelations[0].config.references,
      references: reverseRelations[0].config.fields
    };
  }
  throw new Error(
    `There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`
  );
}
function createTableRelationsHelpers(sourceTable) {
  return {
    one: createOne(sourceTable),
    many: createMany(sourceTable)
  };
}
function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) {
  const result = {};
  for (const [
    selectionItemIndex,
    selectionItem
  ] of buildQueryResultSelection.entries()) {
    if (selectionItem.isJson) {
      const relation = tableConfig.relations[selectionItem.tsKey];
      const rawSubRows = row[selectionItemIndex];
      const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows;
      result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow(
        tablesConfig,
        tablesConfig[selectionItem.relationTableTsKey],
        subRows,
        selectionItem.selection,
        mapColumnValue
      ) : subRows.map(
        (subRow) => mapRelationalRow(
          tablesConfig,
          tablesConfig[selectionItem.relationTableTsKey],
          subRow,
          selectionItem.selection,
          mapColumnValue
        )
      );
    } else {
      const value = mapColumnValue(row[selectionItemIndex]);
      const field = selectionItem.field;
      let decoder;
      if (is(field, Column2)) {
        decoder = field;
      } else if (is(field, SQL)) {
        decoder = field.decoder;
      } else {
        decoder = field.sql.decoder;
      }
      result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value);
    }
  }
  return result;
}
var _a124, Relation, _a125, Relations, _a126, _b101, _One, One, _a127, _b102, _Many, Many;
var init_relations = __esm({
  "../drizzle-orm/dist/relations.js"() {
    "use strict";
    init_table();
    init_column();
    init_entity();
    init_primary_keys();
    init_expressions();
    init_sql();
    _a124 = entityKind;
    Relation = class {
      constructor(sourceTable, referencedTable, relationName) {
        __publicField(this, "referencedTableName");
        __publicField(this, "fieldName");
        this.sourceTable = sourceTable;
        this.referencedTable = referencedTable;
        this.relationName = relationName;
        this.referencedTableName = referencedTable[Table2.Symbol.Name];
      }
    };
    __publicField(Relation, _a124, "Relation");
    _a125 = entityKind;
    Relations = class {
      constructor(table6, config) {
        this.table = table6;
        this.config = config;
      }
    };
    __publicField(Relations, _a125, "Relations");
    _One = class _One extends (_b101 = Relation, _a126 = entityKind, _b101) {
      constructor(sourceTable, referencedTable, config, isNullable) {
        super(sourceTable, referencedTable, config?.relationName);
        this.config = config;
        this.isNullable = isNullable;
      }
      withFieldName(fieldName) {
        const relation = new _One(
          this.sourceTable,
          this.referencedTable,
          this.config,
          this.isNullable
        );
        relation.fieldName = fieldName;
        return relation;
      }
    };
    __publicField(_One, _a126, "One");
    One = _One;
    _Many = class _Many extends (_b102 = Relation, _a127 = entityKind, _b102) {
      constructor(sourceTable, referencedTable, config) {
        super(sourceTable, referencedTable, config?.relationName);
        this.config = config;
      }
      withFieldName(fieldName) {
        const relation = new _Many(
          this.sourceTable,
          this.referencedTable,
          this.config
        );
        relation.fieldName = fieldName;
        return relation;
      }
    };
    __publicField(_Many, _a127, "Many");
    Many = _Many;
  }
});

// ../drizzle-orm/dist/sql/functions/aggregate.js
function count(expression) {
  return sql`count(${expression || sql.raw("*")})`.mapWith(Number);
}
function countDistinct(expression) {
  return sql`count(distinct ${expression})`.mapWith(Number);
}
function avg(expression) {
  return sql`avg(${expression})`.mapWith(String);
}
function avgDistinct(expression) {
  return sql`avg(distinct ${expression})`.mapWith(String);
}
function sum(expression) {
  return sql`sum(${expression})`.mapWith(String);
}
function sumDistinct(expression) {
  return sql`sum(distinct ${expression})`.mapWith(String);
}
function max(expression) {
  return sql`max(${expression})`.mapWith(is(expression, Column2) ? expression : String);
}
function min(expression) {
  return sql`min(${expression})`.mapWith(is(expression, Column2) ? expression : String);
}
var init_aggregate = __esm({
  "../drizzle-orm/dist/sql/functions/aggregate.js"() {
    "use strict";
    init_column();
    init_entity();
    init_sql();
  }
});

// ../drizzle-orm/dist/sql/functions/vector.js
function toSql(value) {
  return JSON.stringify(value);
}
function l2Distance(column6, value) {
  if (Array.isArray(value)) {
    return sql`${column6} <-> ${toSql(value)}`;
  }
  return sql`${column6} <-> ${value}`;
}
function l1Distance(column6, value) {
  if (Array.isArray(value)) {
    return sql`${column6} <+> ${toSql(value)}`;
  }
  return sql`${column6} <+> ${value}`;
}
function innerProduct(column6, value) {
  if (Array.isArray(value)) {
    return sql`${column6} <#> ${toSql(value)}`;
  }
  return sql`${column6} <#> ${value}`;
}
function cosineDistance(column6, value) {
  if (Array.isArray(value)) {
    return sql`${column6} <=> ${toSql(value)}`;
  }
  return sql`${column6} <=> ${value}`;
}
function hammingDistance(column6, value) {
  if (Array.isArray(value)) {
    return sql`${column6} <~> ${toSql(value)}`;
  }
  return sql`${column6} <~> ${value}`;
}
function jaccardDistance(column6, value) {
  if (Array.isArray(value)) {
    return sql`${column6} <%> ${toSql(value)}`;
  }
  return sql`${column6} <%> ${value}`;
}
var init_vector2 = __esm({
  "../drizzle-orm/dist/sql/functions/vector.js"() {
    "use strict";
    init_sql();
  }
});

// ../drizzle-orm/dist/sql/functions/index.js
var init_functions = __esm({
  "../drizzle-orm/dist/sql/functions/index.js"() {
    "use strict";
    init_aggregate();
    init_vector2();
  }
});

// ../drizzle-orm/dist/sql/index.js
var init_sql2 = __esm({
  "../drizzle-orm/dist/sql/index.js"() {
    "use strict";
    init_expressions();
    init_functions();
    init_sql();
  }
});

// ../drizzle-orm/dist/index.js
var dist_exports = {};
__export(dist_exports, {
  BaseName: () => BaseName,
  Column: () => Column2,
  ColumnAliasProxyHandler: () => ColumnAliasProxyHandler,
  ColumnBuilder: () => ColumnBuilder,
  Columns: () => Columns,
  ConsoleLogWriter: () => ConsoleLogWriter,
  DefaultLogger: () => DefaultLogger,
  DrizzleError: () => DrizzleError,
  ExtraConfigBuilder: () => ExtraConfigBuilder,
  ExtraConfigColumns: () => ExtraConfigColumns,
  FakePrimitiveParam: () => FakePrimitiveParam,
  IsAlias: () => IsAlias,
  Many: () => Many,
  Name: () => Name,
  NoopLogger: () => NoopLogger,
  One: () => One,
  OriginalName: () => OriginalName,
  Param: () => Param,
  Placeholder: () => Placeholder,
  QueryPromise: () => QueryPromise,
  Relation: () => Relation,
  RelationTableAliasProxyHandler: () => RelationTableAliasProxyHandler,
  Relations: () => Relations,
  SQL: () => SQL,
  Schema: () => Schema,
  StringChunk: () => StringChunk,
  Subquery: () => Subquery,
  Table: () => Table2,
  TableAliasProxyHandler: () => TableAliasProxyHandler,
  TransactionRollbackError: () => TransactionRollbackError,
  View: () => View3,
  ViewBaseConfig: () => ViewBaseConfig,
  WithSubquery: () => WithSubquery,
  aliasedRelation: () => aliasedRelation,
  aliasedTable: () => aliasedTable,
  aliasedTableColumn: () => aliasedTableColumn,
  and: () => and,
  applyMixins: () => applyMixins,
  arrayContained: () => arrayContained,
  arrayContains: () => arrayContains,
  arrayOverlaps: () => arrayOverlaps,
  asc: () => asc,
  avg: () => avg,
  avgDistinct: () => avgDistinct,
  between: () => between,
  bindIfParam: () => bindIfParam,
  cosineDistance: () => cosineDistance,
  count: () => count,
  countDistinct: () => countDistinct,
  createMany: () => createMany,
  createOne: () => createOne,
  createTableRelationsHelpers: () => createTableRelationsHelpers,
  desc: () => desc,
  entityKind: () => entityKind,
  eq: () => eq,
  exists: () => exists,
  extractTablesRelationalConfig: () => extractTablesRelationalConfig,
  fillPlaceholders: () => fillPlaceholders,
  getColumnNameAndConfig: () => getColumnNameAndConfig,
  getOperators: () => getOperators,
  getOrderByOperators: () => getOrderByOperators,
  getTableColumns: () => getTableColumns,
  getTableLikeName: () => getTableLikeName,
  getTableName: () => getTableName,
  getTableUniqueName: () => getTableUniqueName,
  getViewName: () => getViewName,
  getViewSelectedFields: () => getViewSelectedFields,
  gt: () => gt,
  gte: () => gte,
  hammingDistance: () => hammingDistance,
  hasOwnEntityKind: () => hasOwnEntityKind,
  haveSameKeys: () => haveSameKeys,
  ilike: () => ilike,
  inArray: () => inArray,
  innerProduct: () => innerProduct,
  is: () => is,
  isConfig: () => isConfig,
  isDriverValueEncoder: () => isDriverValueEncoder,
  isNotNull: () => isNotNull,
  isNull: () => isNull,
  isSQLWrapper: () => isSQLWrapper,
  isTable: () => isTable,
  isView: () => isView,
  jaccardDistance: () => jaccardDistance,
  l1Distance: () => l1Distance,
  l2Distance: () => l2Distance,
  like: () => like,
  lt: () => lt,
  lte: () => lte,
  mapColumnsInAliasedSQLToAlias: () => mapColumnsInAliasedSQLToAlias,
  mapColumnsInSQLToAlias: () => mapColumnsInSQLToAlias,
  mapRelationalRow: () => mapRelationalRow,
  mapResultRow: () => mapResultRow,
  mapUpdateSet: () => mapUpdateSet,
  max: () => max,
  min: () => min,
  name: () => name,
  ne: () => ne,
  noopDecoder: () => noopDecoder,
  noopEncoder: () => noopEncoder,
  noopMapper: () => noopMapper,
  normalizeRelation: () => normalizeRelation,
  not: () => not,
  notBetween: () => notBetween,
  notExists: () => notExists,
  notIlike: () => notIlike,
  notInArray: () => notInArray,
  notLike: () => notLike,
  or: () => or,
  orderSelectedFields: () => orderSelectedFields,
  param: () => param,
  placeholder: () => placeholder,
  relations: () => relations,
  sql: () => sql,
  sum: () => sum,
  sumDistinct: () => sumDistinct
});
var init_dist = __esm({
  "../drizzle-orm/dist/index.js"() {
    "use strict";
    init_alias();
    init_column_builder();
    init_column();
    init_entity();
    init_errors2();
    init_logger();
    init_operations();
    init_query_promise();
    init_relations();
    init_sql2();
    init_subquery();
    init_table();
    init_utils2();
    init_view_common();
  }
});

// ../drizzle-orm/dist/pg-core/alias.js
var init_alias2 = __esm({
  "../drizzle-orm/dist/pg-core/alias.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/pg-core/checks.js
var _a128, CheckBuilder, _a129, Check;
var init_checks = __esm({
  "../drizzle-orm/dist/pg-core/checks.js"() {
    "use strict";
    init_entity();
    _a128 = entityKind;
    CheckBuilder = class {
      constructor(name2, value) {
        __publicField(this, "brand");
        this.name = name2;
        this.value = value;
      }
      /** @internal */
      build(table6) {
        return new Check(table6, this);
      }
    };
    __publicField(CheckBuilder, _a128, "PgCheckBuilder");
    _a129 = entityKind;
    Check = class {
      constructor(table6, builder) {
        __publicField(this, "name");
        __publicField(this, "value");
        this.table = table6;
        this.name = builder.name;
        this.value = builder.value;
      }
    };
    __publicField(Check, _a129, "PgCheck");
  }
});

// ../drizzle-orm/dist/pg-core/columns/index.js
var init_columns = __esm({
  "../drizzle-orm/dist/pg-core/columns/index.js"() {
    "use strict";
    init_bigint();
    init_bigserial();
    init_boolean();
    init_char();
    init_cidr();
    init_common2();
    init_custom();
    init_date();
    init_double_precision();
    init_enum();
    init_inet();
    init_int_common();
    init_integer();
    init_interval();
    init_json();
    init_jsonb();
    init_line();
    init_macaddr();
    init_macaddr8();
    init_numeric();
    init_point();
    init_geometry();
    init_real();
    init_serial();
    init_smallint();
    init_smallserial();
    init_text();
    init_time();
    init_timestamp();
    init_uuid();
    init_varchar();
    init_bit();
    init_halfvec();
    init_sparsevec();
    init_vector();
  }
});

// ../drizzle-orm/dist/selection-proxy.js
var _a130, _SelectionProxyHandler, SelectionProxyHandler;
var init_selection_proxy = __esm({
  "../drizzle-orm/dist/selection-proxy.js"() {
    "use strict";
    init_alias();
    init_column();
    init_entity();
    init_sql();
    init_subquery();
    init_view_common();
    _a130 = entityKind;
    _SelectionProxyHandler = class _SelectionProxyHandler {
      constructor(config) {
        __publicField(this, "config");
        this.config = { ...config };
      }
      get(subquery, prop) {
        if (prop === "_") {
          return {
            ...subquery["_"],
            selectedFields: new Proxy(
              subquery._.selectedFields,
              this
            )
          };
        }
        if (prop === ViewBaseConfig) {
          return {
            ...subquery[ViewBaseConfig],
            selectedFields: new Proxy(
              subquery[ViewBaseConfig].selectedFields,
              this
            )
          };
        }
        if (typeof prop === "symbol") {
          return subquery[prop];
        }
        const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View3) ? subquery[ViewBaseConfig].selectedFields : subquery;
        const value = columns[prop];
        if (is(value, SQL.Aliased)) {
          if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) {
            return value.sql;
          }
          const newValue = value.clone();
          newValue.isSelectionField = true;
          return newValue;
        }
        if (is(value, SQL)) {
          if (this.config.sqlBehavior === "sql") {
            return value;
          }
          throw new Error(
            `You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`
          );
        }
        if (is(value, Column2)) {
          if (this.config.alias) {
            return new Proxy(
              value,
              new ColumnAliasProxyHandler(
                new Proxy(
                  value.table,
                  new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false)
                )
              )
            );
          }
          return value;
        }
        if (typeof value !== "object" || value === null) {
          return value;
        }
        return new Proxy(value, new _SelectionProxyHandler(this.config));
      }
    };
    __publicField(_SelectionProxyHandler, _a130, "SelectionProxyHandler");
    SelectionProxyHandler = _SelectionProxyHandler;
  }
});

// ../drizzle-orm/dist/pg-core/indexes.js
var _a131, IndexBuilderOn, _a132, IndexBuilder, _a133, Index2;
var init_indexes = __esm({
  "../drizzle-orm/dist/pg-core/indexes.js"() {
    "use strict";
    init_sql();
    init_entity();
    init_columns();
    _a131 = entityKind;
    IndexBuilderOn = class {
      constructor(unique, name2) {
        this.unique = unique;
        this.name = name2;
      }
      on(...columns) {
        return new IndexBuilder(
          columns.map((it) => {
            if (is(it, SQL)) {
              return it;
            }
            it = it;
            const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
            it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig));
            return clonedIndexedColumn;
          }),
          this.unique,
          false,
          this.name
        );
      }
      onOnly(...columns) {
        return new IndexBuilder(
          columns.map((it) => {
            if (is(it, SQL)) {
              return it;
            }
            it = it;
            const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
            it.indexConfig = it.defaultConfig;
            return clonedIndexedColumn;
          }),
          this.unique,
          true,
          this.name
        );
      }
      /**
       * Specify what index method to use. Choices are `btree`, `hash`, `gist`, `spgist`, `gin`, `brin`, or user-installed access methods like `bloom`. The default method is `btree.
       *
       * If you have the `pg_vector` extension installed in your database, you can use the `hnsw` and `ivfflat` options, which are predefined types.
       *
       * **You can always specify any string you want in the method, in case Drizzle doesn't have it natively in its types**
       *
       * @param method The name of the index method to be used
       * @param columns
       * @returns
       */
      using(method, ...columns) {
        return new IndexBuilder(
          columns.map((it) => {
            if (is(it, SQL)) {
              return it;
            }
            it = it;
            const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig);
            it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig));
            return clonedIndexedColumn;
          }),
          this.unique,
          true,
          this.name,
          method
        );
      }
    };
    __publicField(IndexBuilderOn, _a131, "PgIndexBuilderOn");
    _a132 = entityKind;
    IndexBuilder = class {
      constructor(columns, unique, only, name2, method = "btree") {
        /** @internal */
        __publicField(this, "config");
        this.config = {
          name: name2,
          columns,
          unique,
          only,
          method
        };
      }
      concurrently() {
        this.config.concurrently = true;
        return this;
      }
      with(obj) {
        this.config.with = obj;
        return this;
      }
      where(condition) {
        this.config.where = condition;
        return this;
      }
      /** @internal */
      build(table6) {
        return new Index2(this.config, table6);
      }
    };
    __publicField(IndexBuilder, _a132, "PgIndexBuilder");
    _a133 = entityKind;
    Index2 = class {
      constructor(config, table6) {
        __publicField(this, "config");
        this.config = { ...config, table: table6 };
      }
    };
    __publicField(Index2, _a133, "PgIndex");
  }
});

// ../drizzle-orm/dist/pg-core/policies.js
var _a134, PgPolicy;
var init_policies = __esm({
  "../drizzle-orm/dist/pg-core/policies.js"() {
    "use strict";
    init_entity();
    _a134 = entityKind;
    PgPolicy = class {
      constructor(name2, config) {
        __publicField(this, "as");
        __publicField(this, "for");
        __publicField(this, "to");
        __publicField(this, "using");
        __publicField(this, "withCheck");
        /** @internal */
        __publicField(this, "_linkedTable");
        this.name = name2;
        if (config) {
          this.as = config.as;
          this.for = config.for;
          this.to = config.to;
          this.using = config.using;
          this.withCheck = config.withCheck;
        }
      }
      link(table6) {
        this._linkedTable = table6;
        return this;
      }
    };
    __publicField(PgPolicy, _a134, "PgPolicy");
  }
});

// ../drizzle-orm/dist/pg-core/view-common.js
var PgViewConfig;
var init_view_common2 = __esm({
  "../drizzle-orm/dist/pg-core/view-common.js"() {
    "use strict";
    PgViewConfig = Symbol.for("drizzle:PgViewConfig");
  }
});

// ../drizzle-orm/dist/casing.js
function toSnakeCase(input) {
  const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
  return words.map((word) => word.toLowerCase()).join("_");
}
function toCamelCase(input) {
  const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? [];
  return words.reduce((acc, word, i) => {
    const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`;
    return acc + formattedWord;
  }, "");
}
function noopCase(input) {
  return input;
}
var _a135, CasingCache;
var init_casing = __esm({
  "../drizzle-orm/dist/casing.js"() {
    "use strict";
    init_entity();
    init_table();
    _a135 = entityKind;
    CasingCache = class {
      constructor(casing2) {
        /** @internal */
        __publicField(this, "cache", {});
        __publicField(this, "cachedTables", {});
        __publicField(this, "convert");
        this.convert = casing2 === "snake_case" ? toSnakeCase : casing2 === "camelCase" ? toCamelCase : noopCase;
      }
      getColumnCasing(column6) {
        if (!column6.keyAsName) return column6.name;
        const schema5 = column6.table[Table2.Symbol.Schema] ?? "public";
        const tableName = column6.table[Table2.Symbol.OriginalName];
        const key = `${schema5}.${tableName}.${column6.name}`;
        if (!this.cache[key]) {
          this.cacheTable(column6.table);
        }
        return this.cache[key];
      }
      cacheTable(table6) {
        const schema5 = table6[Table2.Symbol.Schema] ?? "public";
        const tableName = table6[Table2.Symbol.OriginalName];
        const tableKey2 = `${schema5}.${tableName}`;
        if (!this.cachedTables[tableKey2]) {
          for (const column6 of Object.values(table6[Table2.Symbol.Columns])) {
            const columnKey = `${tableKey2}.${column6.name}`;
            this.cache[columnKey] = this.convert(column6.name);
          }
          this.cachedTables[tableKey2] = true;
        }
      }
      clearCache() {
        this.cache = {};
        this.cachedTables = {};
      }
    };
    __publicField(CasingCache, _a135, "CasingCache");
  }
});

// ../drizzle-orm/dist/pg-core/view-base.js
var _a136, _b103, PgViewBase;
var init_view_base = __esm({
  "../drizzle-orm/dist/pg-core/view-base.js"() {
    "use strict";
    init_entity();
    init_sql();
    PgViewBase = class extends (_b103 = View3, _a136 = entityKind, _b103) {
    };
    __publicField(PgViewBase, _a136, "PgViewBase");
  }
});

// ../drizzle-orm/dist/pg-core/dialect.js
var _a137, PgDialect;
var init_dialect = __esm({
  "../drizzle-orm/dist/pg-core/dialect.js"() {
    "use strict";
    init_alias();
    init_casing();
    init_column();
    init_entity();
    init_errors2();
    init_columns();
    init_table2();
    init_relations();
    init_sql2();
    init_sql();
    init_subquery();
    init_table();
    init_utils2();
    init_view_common();
    init_view_base();
    _a137 = entityKind;
    PgDialect = class {
      constructor(config) {
        /** @internal */
        __publicField(this, "casing");
        this.casing = new CasingCache(config?.casing);
      }
      async migrate(migrations, session, config) {
        const migrationsTable = typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
        const migrationsSchema = typeof config === "string" ? "drizzle" : config.migrationsSchema ?? "drizzle";
        const migrationTableCreate = sql`
			CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} (
				id SERIAL PRIMARY KEY,
				hash text NOT NULL,
				created_at bigint
			)
		`;
        await session.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`);
        await session.execute(migrationTableCreate);
        const dbMigrations = await session.all(
          sql`select id, hash, created_at from ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} order by created_at desc limit 1`
        );
        const lastDbMigration = dbMigrations[0];
        await session.transaction(async (tx) => {
          for await (const migration of migrations) {
            if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) {
              for (const stmt of migration.sql) {
                await tx.execute(sql.raw(stmt));
              }
              await tx.execute(
                sql`insert into ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})`
              );
            }
          }
        });
      }
      escapeName(name2) {
        return `"${name2}"`;
      }
      escapeParam(num) {
        return `$${num + 1}`;
      }
      escapeString(str) {
        return `'${str.replace(/'/g, "''")}'`;
      }
      buildWithCTE(queries) {
        if (!queries?.length) return void 0;
        const withSqlChunks = [sql`with `];
        for (const [i, w] of queries.entries()) {
          withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
          if (i < queries.length - 1) {
            withSqlChunks.push(sql`, `);
          }
        }
        withSqlChunks.push(sql` `);
        return sql.join(withSqlChunks);
      }
      buildDeleteQuery({ table: table6, where, returning, withList }) {
        const withSql = this.buildWithCTE(withList);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const whereSql = where ? sql` where ${where}` : void 0;
        return sql`${withSql}delete from ${table6}${whereSql}${returningSql}`;
      }
      buildUpdateSet(table6, set) {
        const tableColumns = table6[Table2.Symbol.Columns];
        const columnNames = Object.keys(tableColumns).filter(
          (colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0
        );
        const setSize = columnNames.length;
        return sql.join(columnNames.flatMap((colName, i) => {
          const col = tableColumns[colName];
          const value = set[colName] ?? sql.param(col.onUpdateFn(), col);
          const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
          if (i < setSize - 1) {
            return [res, sql.raw(", ")];
          }
          return [res];
        }));
      }
      buildUpdateQuery({ table: table6, set, where, returning, withList, from, joins }) {
        const withSql = this.buildWithCTE(withList);
        const tableName = table6[PgTable.Symbol.Name];
        const tableSchema = table6[PgTable.Symbol.Schema];
        const origTableName = table6[PgTable.Symbol.OriginalName];
        const alias = tableName === origTableName ? void 0 : tableName;
        const tableSql = sql`${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}`;
        const setSql = this.buildUpdateSet(table6, set);
        const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]);
        const joinsSql = this.buildJoins(joins);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: !from })}` : void 0;
        const whereSql = where ? sql` where ${where}` : void 0;
        return sql`${withSql}update ${tableSql} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}`;
      }
      /**
       * Builds selection SQL with provided fields/expressions
       *
       * Examples:
       *
       * `select <selection> from`
       *
       * `insert ... returning <selection>`
       *
       * If `isSingleTable` is true, then columns won't be prefixed with table name
       */
      buildSelection(fields, { isSingleTable = false } = {}) {
        const columnsLen = fields.length;
        const chunks = fields.flatMap(({ field }, i) => {
          const chunk = [];
          if (is(field, SQL.Aliased) && field.isSelectionField) {
            chunk.push(sql.identifier(field.fieldAlias));
          } else if (is(field, SQL.Aliased) || is(field, SQL)) {
            const query = is(field, SQL.Aliased) ? field.sql : field;
            if (isSingleTable) {
              chunk.push(
                new SQL(
                  query.queryChunks.map((c) => {
                    if (is(c, PgColumn)) {
                      return sql.identifier(this.casing.getColumnCasing(c));
                    }
                    return c;
                  })
                )
              );
            } else {
              chunk.push(query);
            }
            if (is(field, SQL.Aliased)) {
              chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
            }
          } else if (is(field, Column2)) {
            if (isSingleTable) {
              chunk.push(sql.identifier(this.casing.getColumnCasing(field)));
            } else {
              chunk.push(field);
            }
          }
          if (i < columnsLen - 1) {
            chunk.push(sql`, `);
          }
          return chunk;
        });
        return sql.join(chunks);
      }
      buildJoins(joins) {
        if (!joins || joins.length === 0) {
          return void 0;
        }
        const joinsArray = [];
        for (const [index6, joinMeta] of joins.entries()) {
          if (index6 === 0) {
            joinsArray.push(sql` `);
          }
          const table6 = joinMeta.table;
          const lateralSql = joinMeta.lateral ? sql` lateral` : void 0;
          const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0;
          if (is(table6, PgTable)) {
            const tableName = table6[PgTable.Symbol.Name];
            const tableSchema = table6[PgTable.Symbol.Schema];
            const origTableName = table6[PgTable.Symbol.OriginalName];
            const alias = tableName === origTableName ? void 0 : joinMeta.alias;
            joinsArray.push(
              sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`
            );
          } else if (is(table6, View3)) {
            const viewName = table6[ViewBaseConfig].name;
            const viewSchema = table6[ViewBaseConfig].schema;
            const origViewName = table6[ViewBaseConfig].originalName;
            const alias = viewName === origViewName ? void 0 : joinMeta.alias;
            joinsArray.push(
              sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : void 0}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`
            );
          } else {
            joinsArray.push(
              sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table6}${onSql}`
            );
          }
          if (index6 < joins.length - 1) {
            joinsArray.push(sql` `);
          }
        }
        return sql.join(joinsArray);
      }
      buildFromTable(table6) {
        if (is(table6, Table2) && table6[Table2.Symbol.IsAlias]) {
          let fullName = sql`${sql.identifier(table6[Table2.Symbol.OriginalName])}`;
          if (table6[Table2.Symbol.Schema]) {
            fullName = sql`${sql.identifier(table6[Table2.Symbol.Schema])}.${fullName}`;
          }
          return sql`${fullName} ${sql.identifier(table6[Table2.Symbol.Name])}`;
        }
        return table6;
      }
      buildSelectQuery({
        withList,
        fields,
        fieldsFlat,
        where,
        having,
        table: table6,
        joins,
        orderBy,
        groupBy,
        limit,
        offset,
        lockingClause,
        distinct,
        setOperators
      }) {
        const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
        for (const f of fieldsList) {
          if (is(f.field, Column2) && getTableName(f.field.table) !== (is(table6, Subquery) ? table6._.alias : is(table6, PgViewBase) ? table6[ViewBaseConfig].name : is(table6, SQL) ? void 0 : getTableName(table6)) && !((table22) => joins?.some(
            ({ alias }) => alias === (table22[Table2.Symbol.IsAlias] ? getTableName(table22) : table22[Table2.Symbol.BaseName])
          ))(f.field.table)) {
            const tableName = getTableName(f.field.table);
            throw new Error(
              `Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`
            );
          }
        }
        const isSingleTable = !joins || joins.length === 0;
        const withSql = this.buildWithCTE(withList);
        let distinctSql;
        if (distinct) {
          distinctSql = distinct === true ? sql` distinct` : sql` distinct on (${sql.join(distinct.on, sql`, `)})`;
        }
        const selection = this.buildSelection(fieldsList, { isSingleTable });
        const tableSql = this.buildFromTable(table6);
        const joinsSql = this.buildJoins(joins);
        const whereSql = where ? sql` where ${where}` : void 0;
        const havingSql = having ? sql` having ${having}` : void 0;
        let orderBySql;
        if (orderBy && orderBy.length > 0) {
          orderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`;
        }
        let groupBySql;
        if (groupBy && groupBy.length > 0) {
          groupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`;
        }
        const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
        const offsetSql = offset ? sql` offset ${offset}` : void 0;
        const lockingClauseSql = sql.empty();
        if (lockingClause) {
          const clauseSql = sql` for ${sql.raw(lockingClause.strength)}`;
          if (lockingClause.config.of) {
            clauseSql.append(
              sql` of ${sql.join(
                Array.isArray(lockingClause.config.of) ? lockingClause.config.of : [lockingClause.config.of],
                sql`, `
              )}`
            );
          }
          if (lockingClause.config.noWait) {
            clauseSql.append(sql` nowait`);
          } else if (lockingClause.config.skipLocked) {
            clauseSql.append(sql` skip locked`);
          }
          lockingClauseSql.append(clauseSql);
        }
        const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}`;
        if (setOperators.length > 0) {
          return this.buildSetOperations(finalQuery, setOperators);
        }
        return finalQuery;
      }
      buildSetOperations(leftSelect, setOperators) {
        const [setOperator, ...rest] = setOperators;
        if (!setOperator) {
          throw new Error("Cannot pass undefined values to any set operator");
        }
        if (rest.length === 0) {
          return this.buildSetOperationQuery({ leftSelect, setOperator });
        }
        return this.buildSetOperations(
          this.buildSetOperationQuery({ leftSelect, setOperator }),
          rest
        );
      }
      buildSetOperationQuery({
        leftSelect,
        setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
      }) {
        const leftChunk = sql`(${leftSelect.getSQL()}) `;
        const rightChunk = sql`(${rightSelect.getSQL()})`;
        let orderBySql;
        if (orderBy && orderBy.length > 0) {
          const orderByValues = [];
          for (const singleOrderBy of orderBy) {
            if (is(singleOrderBy, PgColumn)) {
              orderByValues.push(sql.identifier(singleOrderBy.name));
            } else if (is(singleOrderBy, SQL)) {
              for (let i = 0; i < singleOrderBy.queryChunks.length; i++) {
                const chunk = singleOrderBy.queryChunks[i];
                if (is(chunk, PgColumn)) {
                  singleOrderBy.queryChunks[i] = sql.identifier(chunk.name);
                }
              }
              orderByValues.push(sql`${singleOrderBy}`);
            } else {
              orderByValues.push(sql`${singleOrderBy}`);
            }
          }
          orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `;
        }
        const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
        const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
        const offsetSql = offset ? sql` offset ${offset}` : void 0;
        return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
      }
      buildInsertQuery({ table: table6, values: valuesOrSelect, onConflict, returning, withList, select, overridingSystemValue_ }) {
        const valuesSqlList = [];
        const columns = table6[Table2.Symbol.Columns];
        const colEntries = Object.entries(columns).filter(([_2, col]) => !col.shouldDisableInsert());
        const insertOrder = colEntries.map(
          ([, column6]) => sql.identifier(this.casing.getColumnCasing(column6))
        );
        if (select) {
          const select2 = valuesOrSelect;
          if (is(select2, SQL)) {
            valuesSqlList.push(select2);
          } else {
            valuesSqlList.push(select2.getSQL());
          }
        } else {
          const values = valuesOrSelect;
          valuesSqlList.push(sql.raw("values "));
          for (const [valueIndex, value] of values.entries()) {
            const valueList = [];
            for (const [fieldName, col] of colEntries) {
              const colValue = value[fieldName];
              if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
                if (col.defaultFn !== void 0) {
                  const defaultFnResult = col.defaultFn();
                  const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
                  valueList.push(defaultValue);
                } else if (!col.default && col.onUpdateFn !== void 0) {
                  const onUpdateFnResult = col.onUpdateFn();
                  const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
                  valueList.push(newValue);
                } else {
                  valueList.push(sql`default`);
                }
              } else {
                valueList.push(colValue);
              }
            }
            valuesSqlList.push(valueList);
            if (valueIndex < values.length - 1) {
              valuesSqlList.push(sql`, `);
            }
          }
        }
        const withSql = this.buildWithCTE(withList);
        const valuesSql = sql.join(valuesSqlList);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0;
        const overridingSql = overridingSystemValue_ === true ? sql`overriding system value ` : void 0;
        return sql`${withSql}insert into ${table6} ${insertOrder} ${overridingSql}${valuesSql}${onConflictSql}${returningSql}`;
      }
      buildRefreshMaterializedViewQuery({ view: view5, concurrently, withNoData }) {
        const concurrentlySql = concurrently ? sql` concurrently` : void 0;
        const withNoDataSql = withNoData ? sql` with no data` : void 0;
        return sql`refresh materialized view${concurrentlySql} ${view5}${withNoDataSql}`;
      }
      prepareTyping(encoder) {
        if (is(encoder, PgJsonb) || is(encoder, PgJson)) {
          return "json";
        } else if (is(encoder, PgNumeric)) {
          return "decimal";
        } else if (is(encoder, PgTime)) {
          return "time";
        } else if (is(encoder, PgTimestamp) || is(encoder, PgTimestampString)) {
          return "timestamp";
        } else if (is(encoder, PgDate) || is(encoder, PgDateString)) {
          return "date";
        } else if (is(encoder, PgUUID)) {
          return "uuid";
        } else {
          return "none";
        }
      }
      sqlToQuery(sql2, invokeSource) {
        return sql2.toQuery({
          casing: this.casing,
          escapeName: this.escapeName,
          escapeParam: this.escapeParam,
          escapeString: this.escapeString,
          prepareTyping: this.prepareTyping,
          invokeSource
        });
      }
      // buildRelationalQueryWithPK({
      // 	fullSchema,
      // 	schema,
      // 	tableNamesMap,
      // 	table,
      // 	tableConfig,
      // 	queryConfig: config,
      // 	tableAlias,
      // 	isRoot = false,
      // 	joinOn,
      // }: {
      // 	fullSchema: Record<string, unknown>;
      // 	schema: TablesRelationalConfig;
      // 	tableNamesMap: Record<string, string>;
      // 	table: PgTable;
      // 	tableConfig: TableRelationalConfig;
      // 	queryConfig: true | DBQueryConfig<'many', true>;
      // 	tableAlias: string;
      // 	isRoot?: boolean;
      // 	joinOn?: SQL;
      // }): BuildRelationalQueryResult<PgTable, PgColumn> {
      // 	// For { "<relation>": true }, return a table with selection of all columns
      // 	if (config === true) {
      // 		const selectionEntries = Object.entries(tableConfig.columns);
      // 		const selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = selectionEntries.map((
      // 			[key, value],
      // 		) => ({
      // 			dbKey: value.name,
      // 			tsKey: key,
      // 			field: value as PgColumn,
      // 			relationTableTsKey: undefined,
      // 			isJson: false,
      // 			selection: [],
      // 		}));
      // 		return {
      // 			tableTsKey: tableConfig.tsName,
      // 			sql: table,
      // 			selection,
      // 		};
      // 	}
      // 	// let selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = [];
      // 	// let selectionForBuild = selection;
      // 	const aliasedColumns = Object.fromEntries(
      // 		Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)]),
      // 	);
      // 	const aliasedRelations = Object.fromEntries(
      // 		Object.entries(tableConfig.relations).map(([key, value]) => [key, aliasedRelation(value, tableAlias)]),
      // 	);
      // 	const aliasedFields = Object.assign({}, aliasedColumns, aliasedRelations);
      // 	let where, hasUserDefinedWhere;
      // 	if (config.where) {
      // 		const whereSql = typeof config.where === 'function' ? config.where(aliasedFields, operators) : config.where;
      // 		where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
      // 		hasUserDefinedWhere = !!where;
      // 	}
      // 	where = and(joinOn, where);
      // 	// const fieldsSelection: { tsKey: string; value: PgColumn | SQL.Aliased; isExtra?: boolean }[] = [];
      // 	let joins: Join[] = [];
      // 	let selectedColumns: string[] = [];
      // 	// Figure out which columns to select
      // 	if (config.columns) {
      // 		let isIncludeMode = false;
      // 		for (const [field, value] of Object.entries(config.columns)) {
      // 			if (value === undefined) {
      // 				continue;
      // 			}
      // 			if (field in tableConfig.columns) {
      // 				if (!isIncludeMode && value === true) {
      // 					isIncludeMode = true;
      // 				}
      // 				selectedColumns.push(field);
      // 			}
      // 		}
      // 		if (selectedColumns.length > 0) {
      // 			selectedColumns = isIncludeMode
      // 				? selectedColumns.filter((c) => config.columns?.[c] === true)
      // 				: Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
      // 		}
      // 	} else {
      // 		// Select all columns if selection is not specified
      // 		selectedColumns = Object.keys(tableConfig.columns);
      // 	}
      // 	// for (const field of selectedColumns) {
      // 	// 	const column = tableConfig.columns[field]! as PgColumn;
      // 	// 	fieldsSelection.push({ tsKey: field, value: column });
      // 	// }
      // 	let initiallySelectedRelations: {
      // 		tsKey: string;
      // 		queryConfig: true | DBQueryConfig<'many', false>;
      // 		relation: Relation;
      // 	}[] = [];
      // 	// let selectedRelations: BuildRelationalQueryResult<PgTable, PgColumn>['selection'] = [];
      // 	// Figure out which relations to select
      // 	if (config.with) {
      // 		initiallySelectedRelations = Object.entries(config.with)
      // 			.filter((entry): entry is [typeof entry[0], NonNullable<typeof entry[1]>] => !!entry[1])
      // 			.map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey]! }));
      // 	}
      // 	const manyRelations = initiallySelectedRelations.filter((r) =>
      // 		is(r.relation, Many)
      // 		&& (schema[tableNamesMap[r.relation.referencedTable[Table.Symbol.Name]]!]?.primaryKey.length ?? 0) > 0
      // 	);
      // 	// If this is the last Many relation (or there are no Many relations), we are on the innermost subquery level
      // 	const isInnermostQuery = manyRelations.length < 2;
      // 	const selectedExtras: {
      // 		tsKey: string;
      // 		value: SQL.Aliased;
      // 	}[] = [];
      // 	// Figure out which extras to select
      // 	if (isInnermostQuery && config.extras) {
      // 		const extras = typeof config.extras === 'function'
      // 			? config.extras(aliasedFields, { sql })
      // 			: config.extras;
      // 		for (const [tsKey, value] of Object.entries(extras)) {
      // 			selectedExtras.push({
      // 				tsKey,
      // 				value: mapColumnsInAliasedSQLToAlias(value, tableAlias),
      // 			});
      // 		}
      // 	}
      // 	// Transform `fieldsSelection` into `selection`
      // 	// `fieldsSelection` shouldn't be used after this point
      // 	// for (const { tsKey, value, isExtra } of fieldsSelection) {
      // 	// 	selection.push({
      // 	// 		dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey]!.name,
      // 	// 		tsKey,
      // 	// 		field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value,
      // 	// 		relationTableTsKey: undefined,
      // 	// 		isJson: false,
      // 	// 		isExtra,
      // 	// 		selection: [],
      // 	// 	});
      // 	// }
      // 	let orderByOrig = typeof config.orderBy === 'function'
      // 		? config.orderBy(aliasedFields, orderByOperators)
      // 		: config.orderBy ?? [];
      // 	if (!Array.isArray(orderByOrig)) {
      // 		orderByOrig = [orderByOrig];
      // 	}
      // 	const orderBy = orderByOrig.map((orderByValue) => {
      // 		if (is(orderByValue, Column)) {
      // 			return aliasedTableColumn(orderByValue, tableAlias) as PgColumn;
      // 		}
      // 		return mapColumnsInSQLToAlias(orderByValue, tableAlias);
      // 	});
      // 	const limit = isInnermostQuery ? config.limit : undefined;
      // 	const offset = isInnermostQuery ? config.offset : undefined;
      // 	// For non-root queries without additional config except columns, return a table with selection
      // 	if (
      // 		!isRoot
      // 		&& initiallySelectedRelations.length === 0
      // 		&& selectedExtras.length === 0
      // 		&& !where
      // 		&& orderBy.length === 0
      // 		&& limit === undefined
      // 		&& offset === undefined
      // 	) {
      // 		return {
      // 			tableTsKey: tableConfig.tsName,
      // 			sql: table,
      // 			selection: selectedColumns.map((key) => ({
      // 				dbKey: tableConfig.columns[key]!.name,
      // 				tsKey: key,
      // 				field: tableConfig.columns[key] as PgColumn,
      // 				relationTableTsKey: undefined,
      // 				isJson: false,
      // 				selection: [],
      // 			})),
      // 		};
      // 	}
      // 	const selectedRelationsWithoutPK:
      // 	// Process all relations without primary keys, because they need to be joined differently and will all be on the same query level
      // 	for (
      // 		const {
      // 			tsKey: selectedRelationTsKey,
      // 			queryConfig: selectedRelationConfigValue,
      // 			relation,
      // 		} of initiallySelectedRelations
      // 	) {
      // 		const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
      // 		const relationTableName = relation.referencedTable[Table.Symbol.Name];
      // 		const relationTableTsName = tableNamesMap[relationTableName]!;
      // 		const relationTable = schema[relationTableTsName]!;
      // 		if (relationTable.primaryKey.length > 0) {
      // 			continue;
      // 		}
      // 		const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
      // 		const joinOn = and(
      // 			...normalizedRelation.fields.map((field, i) =>
      // 				eq(
      // 					aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
      // 					aliasedTableColumn(field, tableAlias),
      // 				)
      // 			),
      // 		);
      // 		const builtRelation = this.buildRelationalQueryWithoutPK({
      // 			fullSchema,
      // 			schema,
      // 			tableNamesMap,
      // 			table: fullSchema[relationTableTsName] as PgTable,
      // 			tableConfig: schema[relationTableTsName]!,
      // 			queryConfig: selectedRelationConfigValue,
      // 			tableAlias: relationTableAlias,
      // 			joinOn,
      // 			nestedQueryRelation: relation,
      // 		});
      // 		const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier('data')}`.as(selectedRelationTsKey);
      // 		joins.push({
      // 			on: sql`true`,
      // 			table: new Subquery(builtRelation.sql as SQL, {}, relationTableAlias),
      // 			alias: relationTableAlias,
      // 			joinType: 'left',
      // 			lateral: true,
      // 		});
      // 		selectedRelations.push({
      // 			dbKey: selectedRelationTsKey,
      // 			tsKey: selectedRelationTsKey,
      // 			field,
      // 			relationTableTsKey: relationTableTsName,
      // 			isJson: true,
      // 			selection: builtRelation.selection,
      // 		});
      // 	}
      // 	const oneRelations = initiallySelectedRelations.filter((r): r is typeof r & { relation: One } =>
      // 		is(r.relation, One)
      // 	);
      // 	// Process all One relations with PKs, because they can all be joined on the same level
      // 	for (
      // 		const {
      // 			tsKey: selectedRelationTsKey,
      // 			queryConfig: selectedRelationConfigValue,
      // 			relation,
      // 		} of oneRelations
      // 	) {
      // 		const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
      // 		const relationTableName = relation.referencedTable[Table.Symbol.Name];
      // 		const relationTableTsName = tableNamesMap[relationTableName]!;
      // 		const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
      // 		const relationTable = schema[relationTableTsName]!;
      // 		if (relationTable.primaryKey.length === 0) {
      // 			continue;
      // 		}
      // 		const joinOn = and(
      // 			...normalizedRelation.fields.map((field, i) =>
      // 				eq(
      // 					aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
      // 					aliasedTableColumn(field, tableAlias),
      // 				)
      // 			),
      // 		);
      // 		const builtRelation = this.buildRelationalQueryWithPK({
      // 			fullSchema,
      // 			schema,
      // 			tableNamesMap,
      // 			table: fullSchema[relationTableTsName] as PgTable,
      // 			tableConfig: schema[relationTableTsName]!,
      // 			queryConfig: selectedRelationConfigValue,
      // 			tableAlias: relationTableAlias,
      // 			joinOn,
      // 		});
      // 		const field = sql`case when ${sql.identifier(relationTableAlias)} is null then null else json_build_array(${
      // 			sql.join(
      // 				builtRelation.selection.map(({ field }) =>
      // 					is(field, SQL.Aliased)
      // 						? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
      // 						: is(field, Column)
      // 						? aliasedTableColumn(field, relationTableAlias)
      // 						: field
      // 				),
      // 				sql`, `,
      // 			)
      // 		}) end`.as(selectedRelationTsKey);
      // 		const isLateralJoin = is(builtRelation.sql, SQL);
      // 		joins.push({
      // 			on: isLateralJoin ? sql`true` : joinOn,
      // 			table: is(builtRelation.sql, SQL)
      // 				? new Subquery(builtRelation.sql, {}, relationTableAlias)
      // 				: aliasedTable(builtRelation.sql, relationTableAlias),
      // 			alias: relationTableAlias,
      // 			joinType: 'left',
      // 			lateral: is(builtRelation.sql, SQL),
      // 		});
      // 		selectedRelations.push({
      // 			dbKey: selectedRelationTsKey,
      // 			tsKey: selectedRelationTsKey,
      // 			field,
      // 			relationTableTsKey: relationTableTsName,
      // 			isJson: true,
      // 			selection: builtRelation.selection,
      // 		});
      // 	}
      // 	let distinct: PgSelectConfig['distinct'];
      // 	let tableFrom: PgTable | Subquery = table;
      // 	// Process first Many relation - each one requires a nested subquery
      // 	const manyRelation = manyRelations[0];
      // 	if (manyRelation) {
      // 		const {
      // 			tsKey: selectedRelationTsKey,
      // 			queryConfig: selectedRelationQueryConfig,
      // 			relation,
      // 		} = manyRelation;
      // 		distinct = {
      // 			on: tableConfig.primaryKey.map((c) => aliasedTableColumn(c as PgColumn, tableAlias)),
      // 		};
      // 		const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation);
      // 		const relationTableName = relation.referencedTable[Table.Symbol.Name];
      // 		const relationTableTsName = tableNamesMap[relationTableName]!;
      // 		const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
      // 		const joinOn = and(
      // 			...normalizedRelation.fields.map((field, i) =>
      // 				eq(
      // 					aliasedTableColumn(normalizedRelation.references[i]!, relationTableAlias),
      // 					aliasedTableColumn(field, tableAlias),
      // 				)
      // 			),
      // 		);
      // 		const builtRelationJoin = this.buildRelationalQueryWithPK({
      // 			fullSchema,
      // 			schema,
      // 			tableNamesMap,
      // 			table: fullSchema[relationTableTsName] as PgTable,
      // 			tableConfig: schema[relationTableTsName]!,
      // 			queryConfig: selectedRelationQueryConfig,
      // 			tableAlias: relationTableAlias,
      // 			joinOn,
      // 		});
      // 		const builtRelationSelectionField = sql`case when ${
      // 			sql.identifier(relationTableAlias)
      // 		} is null then '[]' else json_agg(json_build_array(${
      // 			sql.join(
      // 				builtRelationJoin.selection.map(({ field }) =>
      // 					is(field, SQL.Aliased)
      // 						? sql`${sql.identifier(relationTableAlias)}.${sql.identifier(field.fieldAlias)}`
      // 						: is(field, Column)
      // 						? aliasedTableColumn(field, relationTableAlias)
      // 						: field
      // 				),
      // 				sql`, `,
      // 			)
      // 		})) over (partition by ${sql.join(distinct.on, sql`, `)}) end`.as(selectedRelationTsKey);
      // 		const isLateralJoin = is(builtRelationJoin.sql, SQL);
      // 		joins.push({
      // 			on: isLateralJoin ? sql`true` : joinOn,
      // 			table: isLateralJoin
      // 				? new Subquery(builtRelationJoin.sql as SQL, {}, relationTableAlias)
      // 				: aliasedTable(builtRelationJoin.sql as PgTable, relationTableAlias),
      // 			alias: relationTableAlias,
      // 			joinType: 'left',
      // 			lateral: isLateralJoin,
      // 		});
      // 		// Build the "from" subquery with the remaining Many relations
      // 		const builtTableFrom = this.buildRelationalQueryWithPK({
      // 			fullSchema,
      // 			schema,
      // 			tableNamesMap,
      // 			table,
      // 			tableConfig,
      // 			queryConfig: {
      // 				...config,
      // 				where: undefined,
      // 				orderBy: undefined,
      // 				limit: undefined,
      // 				offset: undefined,
      // 				with: manyRelations.slice(1).reduce<NonNullable<typeof config['with']>>(
      // 					(result, { tsKey, queryConfig: configValue }) => {
      // 						result[tsKey] = configValue;
      // 						return result;
      // 					},
      // 					{},
      // 				),
      // 			},
      // 			tableAlias,
      // 		});
      // 		selectedRelations.push({
      // 			dbKey: selectedRelationTsKey,
      // 			tsKey: selectedRelationTsKey,
      // 			field: builtRelationSelectionField,
      // 			relationTableTsKey: relationTableTsName,
      // 			isJson: true,
      // 			selection: builtRelationJoin.selection,
      // 		});
      // 		// selection = builtTableFrom.selection.map((item) =>
      // 		// 	is(item.field, SQL.Aliased)
      // 		// 		? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
      // 		// 		: item
      // 		// );
      // 		// selectionForBuild = [{
      // 		// 	dbKey: '*',
      // 		// 	tsKey: '*',
      // 		// 	field: sql`${sql.identifier(tableAlias)}.*`,
      // 		// 	selection: [],
      // 		// 	isJson: false,
      // 		// 	relationTableTsKey: undefined,
      // 		// }];
      // 		// const newSelectionItem: (typeof selection)[number] = {
      // 		// 	dbKey: selectedRelationTsKey,
      // 		// 	tsKey: selectedRelationTsKey,
      // 		// 	field,
      // 		// 	relationTableTsKey: relationTableTsName,
      // 		// 	isJson: true,
      // 		// 	selection: builtRelationJoin.selection,
      // 		// };
      // 		// selection.push(newSelectionItem);
      // 		// selectionForBuild.push(newSelectionItem);
      // 		tableFrom = is(builtTableFrom.sql, PgTable)
      // 			? builtTableFrom.sql
      // 			: new Subquery(builtTableFrom.sql, {}, tableAlias);
      // 	}
      // 	if (selectedColumns.length === 0 && selectedRelations.length === 0 && selectedExtras.length === 0) {
      // 		throw new DrizzleError(`No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")`);
      // 	}
      // 	let selection: BuildRelationalQueryResult<PgTable, PgColumn>['selection'];
      // 	function prepareSelectedColumns() {
      // 		return selectedColumns.map((key) => ({
      // 			dbKey: tableConfig.columns[key]!.name,
      // 			tsKey: key,
      // 			field: tableConfig.columns[key] as PgColumn,
      // 			relationTableTsKey: undefined,
      // 			isJson: false,
      // 			selection: [],
      // 		}));
      // 	}
      // 	function prepareSelectedExtras() {
      // 		return selectedExtras.map((item) => ({
      // 			dbKey: item.value.fieldAlias,
      // 			tsKey: item.tsKey,
      // 			field: item.value,
      // 			relationTableTsKey: undefined,
      // 			isJson: false,
      // 			selection: [],
      // 		}));
      // 	}
      // 	if (isRoot) {
      // 		selection = [
      // 			...prepareSelectedColumns(),
      // 			...prepareSelectedExtras(),
      // 		];
      // 	}
      // 	if (hasUserDefinedWhere || orderBy.length > 0) {
      // 		tableFrom = new Subquery(
      // 			this.buildSelectQuery({
      // 				table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
      // 				fields: {},
      // 				fieldsFlat: selectionForBuild.map(({ field }) => ({
      // 					path: [],
      // 					field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
      // 				})),
      // 				joins,
      // 				distinct,
      // 			}),
      // 			{},
      // 			tableAlias,
      // 		);
      // 		selectionForBuild = selection.map((item) =>
      // 			is(item.field, SQL.Aliased)
      // 				? { ...item, field: sql`${sql.identifier(tableAlias)}.${sql.identifier(item.field.fieldAlias)}` }
      // 				: item
      // 		);
      // 		joins = [];
      // 		distinct = undefined;
      // 	}
      // 	const result = this.buildSelectQuery({
      // 		table: is(tableFrom, PgTable) ? aliasedTable(tableFrom, tableAlias) : tableFrom,
      // 		fields: {},
      // 		fieldsFlat: selectionForBuild.map(({ field }) => ({
      // 			path: [],
      // 			field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field,
      // 		})),
      // 		where,
      // 		limit,
      // 		offset,
      // 		joins,
      // 		orderBy,
      // 		distinct,
      // 	});
      // 	return {
      // 		tableTsKey: tableConfig.tsName,
      // 		sql: result,
      // 		selection,
      // 	};
      // }
      buildRelationalQueryWithoutPK({
        fullSchema,
        schema: schema5,
        tableNamesMap,
        table: table6,
        tableConfig,
        queryConfig: config,
        tableAlias,
        nestedQueryRelation,
        joinOn
      }) {
        let selection = [];
        let limit, offset, orderBy = [], where;
        const joins = [];
        if (config === true) {
          const selectionEntries = Object.entries(tableConfig.columns);
          selection = selectionEntries.map(([key, value]) => ({
            dbKey: value.name,
            tsKey: key,
            field: aliasedTableColumn(value, tableAlias),
            relationTableTsKey: void 0,
            isJson: false,
            selection: []
          }));
        } else {
          const aliasedColumns = Object.fromEntries(
            Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)])
          );
          if (config.where) {
            const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
            where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
          }
          const fieldsSelection = [];
          let selectedColumns = [];
          if (config.columns) {
            let isIncludeMode = false;
            for (const [field, value] of Object.entries(config.columns)) {
              if (value === void 0) {
                continue;
              }
              if (field in tableConfig.columns) {
                if (!isIncludeMode && value === true) {
                  isIncludeMode = true;
                }
                selectedColumns.push(field);
              }
            }
            if (selectedColumns.length > 0) {
              selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
            }
          } else {
            selectedColumns = Object.keys(tableConfig.columns);
          }
          for (const field of selectedColumns) {
            const column6 = tableConfig.columns[field];
            fieldsSelection.push({ tsKey: field, value: column6 });
          }
          let selectedRelations = [];
          if (config.with) {
            selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
          }
          let extras;
          if (config.extras) {
            extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
            for (const [tsKey, value] of Object.entries(extras)) {
              fieldsSelection.push({
                tsKey,
                value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
              });
            }
          }
          for (const { tsKey, value } of fieldsSelection) {
            selection.push({
              dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
              tsKey,
              field: is(value, Column2) ? aliasedTableColumn(value, tableAlias) : value,
              relationTableTsKey: void 0,
              isJson: false,
              selection: []
            });
          }
          let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
          if (!Array.isArray(orderByOrig)) {
            orderByOrig = [orderByOrig];
          }
          orderBy = orderByOrig.map((orderByValue) => {
            if (is(orderByValue, Column2)) {
              return aliasedTableColumn(orderByValue, tableAlias);
            }
            return mapColumnsInSQLToAlias(orderByValue, tableAlias);
          });
          limit = config.limit;
          offset = config.offset;
          for (const {
            tsKey: selectedRelationTsKey,
            queryConfig: selectedRelationConfigValue,
            relation
          } of selectedRelations) {
            const normalizedRelation = normalizeRelation(schema5, tableNamesMap, relation);
            const relationTableName = getTableUniqueName(relation.referencedTable);
            const relationTableTsName = tableNamesMap[relationTableName];
            const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
            const joinOn2 = and(
              ...normalizedRelation.fields.map(
                (field2, i) => eq(
                  aliasedTableColumn(normalizedRelation.references[i], relationTableAlias),
                  aliasedTableColumn(field2, tableAlias)
                )
              )
            );
            const builtRelation = this.buildRelationalQueryWithoutPK({
              fullSchema,
              schema: schema5,
              tableNamesMap,
              table: fullSchema[relationTableTsName],
              tableConfig: schema5[relationTableTsName],
              queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
              tableAlias: relationTableAlias,
              joinOn: joinOn2,
              nestedQueryRelation: relation
            });
            const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier("data")}`.as(selectedRelationTsKey);
            joins.push({
              on: sql`true`,
              table: new Subquery(builtRelation.sql, {}, relationTableAlias),
              alias: relationTableAlias,
              joinType: "left",
              lateral: true
            });
            selection.push({
              dbKey: selectedRelationTsKey,
              tsKey: selectedRelationTsKey,
              field,
              relationTableTsKey: relationTableTsName,
              isJson: true,
              selection: builtRelation.selection
            });
          }
        }
        if (selection.length === 0) {
          throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` });
        }
        let result;
        where = and(joinOn, where);
        if (nestedQueryRelation) {
          let field = sql`json_build_array(${sql.join(
            selection.map(
              ({ field: field2, tsKey, isJson }) => isJson ? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2
            ),
            sql`, `
          )})`;
          if (is(nestedQueryRelation, Many)) {
            field = sql`coalesce(json_agg(${field}${orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : void 0}), '[]'::json)`;
          }
          const nestedSelection = [{
            dbKey: "data",
            tsKey: "data",
            field: field.as("data"),
            isJson: true,
            relationTableTsKey: tableConfig.tsName,
            selection
          }];
          const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0;
          if (needsSubquery) {
            result = this.buildSelectQuery({
              table: aliasedTable(table6, tableAlias),
              fields: {},
              fieldsFlat: [{
                path: [],
                field: sql.raw("*")
              }],
              where,
              limit,
              offset,
              orderBy,
              setOperators: []
            });
            where = void 0;
            limit = void 0;
            offset = void 0;
            orderBy = [];
          } else {
            result = aliasedTable(table6, tableAlias);
          }
          result = this.buildSelectQuery({
            table: is(result, PgTable) ? result : new Subquery(result, {}, tableAlias),
            fields: {},
            fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
              path: [],
              field: is(field2, Column2) ? aliasedTableColumn(field2, tableAlias) : field2
            })),
            joins,
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        } else {
          result = this.buildSelectQuery({
            table: aliasedTable(table6, tableAlias),
            fields: {},
            fieldsFlat: selection.map(({ field }) => ({
              path: [],
              field: is(field, Column2) ? aliasedTableColumn(field, tableAlias) : field
            })),
            joins,
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        }
        return {
          tableTsKey: tableConfig.tsName,
          sql: result,
          selection
        };
      }
    };
    __publicField(PgDialect, _a137, "PgDialect");
  }
});

// ../drizzle-orm/dist/query-builders/query-builder.js
var _a138, TypedQueryBuilder;
var init_query_builder = __esm({
  "../drizzle-orm/dist/query-builders/query-builder.js"() {
    "use strict";
    init_entity();
    _a138 = entityKind;
    TypedQueryBuilder = class {
      /** @internal */
      getSelectedFields() {
        return this._.selectedFields;
      }
    };
    __publicField(TypedQueryBuilder, _a138, "TypedQueryBuilder");
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/select.js
function createSetOperator(type, isAll) {
  return (leftSelect, rightSelect, ...restSelects) => {
    const setOperators = [rightSelect, ...restSelects].map((select) => ({
      type,
      isAll,
      rightSelect: select
    }));
    for (const setOperator of setOperators) {
      if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
        throw new Error(
          "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
        );
      }
    }
    return leftSelect.addSetOperators(setOperators);
  };
}
var _a139, PgSelectBuilder, _a140, _b104, PgSelectQueryBuilderBase, _a141, _b105, PgSelectBase, getPgSetOperators, union2, unionAll, intersect, intersectAll, except, exceptAll;
var init_select2 = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/select.js"() {
    "use strict";
    init_entity();
    init_view_base();
    init_query_builder();
    init_query_promise();
    init_selection_proxy();
    init_sql();
    init_subquery();
    init_table();
    init_tracing();
    init_utils2();
    init_utils2();
    init_view_common();
    init_utils4();
    _a139 = entityKind;
    PgSelectBuilder = class {
      constructor(config) {
        __publicField(this, "fields");
        __publicField(this, "session");
        __publicField(this, "dialect");
        __publicField(this, "withList", []);
        __publicField(this, "distinct");
        __publicField(this, "authToken");
        this.fields = config.fields;
        this.session = config.session;
        this.dialect = config.dialect;
        if (config.withList) {
          this.withList = config.withList;
        }
        this.distinct = config.distinct;
      }
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
      /**
       * Specify the table, subquery, or other target that you're
       * building a select query against.
       *
       * {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM | Postgres from documentation}
       */
      from(source) {
        const isPartialSelect = !!this.fields;
        const src = source;
        let fields;
        if (this.fields) {
          fields = this.fields;
        } else if (is(src, Subquery)) {
          fields = Object.fromEntries(
            Object.keys(src._.selectedFields).map((key) => [key, src[key]])
          );
        } else if (is(src, PgViewBase)) {
          fields = src[ViewBaseConfig].selectedFields;
        } else if (is(src, SQL)) {
          fields = {};
        } else {
          fields = getTableColumns(src);
        }
        return new PgSelectBase({
          table: src,
          fields,
          isPartialSelect,
          session: this.session,
          dialect: this.dialect,
          withList: this.withList,
          distinct: this.distinct
        }).setToken(this.authToken);
      }
    };
    __publicField(PgSelectBuilder, _a139, "PgSelectBuilder");
    PgSelectQueryBuilderBase = class extends (_b104 = TypedQueryBuilder, _a140 = entityKind, _b104) {
      constructor({ table: table6, fields, isPartialSelect, session, dialect: dialect6, withList, distinct }) {
        super();
        __publicField(this, "_");
        __publicField(this, "config");
        __publicField(this, "joinsNotNullableMap");
        __publicField(this, "tableName");
        __publicField(this, "isPartialSelect");
        __publicField(this, "session");
        __publicField(this, "dialect");
        __publicField(this, "cacheConfig");
        __publicField(this, "usedTables", /* @__PURE__ */ new Set());
        /**
         * Executes a `left join` operation by adding another table to the current query.
         *
         * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select()
         *   .from(users)
         *   .leftJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .leftJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "leftJoin", this.createJoin("left", false));
        /**
         * Executes a `left join lateral` operation by adding subquery to the current query.
         *
         * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
         *
         * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#left-join-lateral}
         *
         * @param table the subquery to join.
         * @param on the `on` clause.
         */
        __publicField(this, "leftJoinLateral", this.createJoin("left", true));
        /**
         * Executes a `right join` operation by adding another table to the current query.
         *
         * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select()
         *   .from(users)
         *   .rightJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .rightJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "rightJoin", this.createJoin("right", false));
        /**
         * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
         *
         * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
         *   .from(users)
         *   .innerJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .innerJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "innerJoin", this.createJoin("inner", false));
        /**
         * Executes an `inner join lateral` operation, creating a new table by combining rows from two queries that have matching values.
         *
         * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
         *
         * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join-lateral}
         *
         * @param table the subquery to join.
         * @param on the `on` clause.
         */
        __publicField(this, "innerJoinLateral", this.createJoin("inner", true));
        /**
         * Executes a `full join` operation by combining rows from two tables into a new table.
         *
         * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User | null; pets: Pet | null; }[] = await db.select()
         *   .from(users)
         *   .fullJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number | null; petId: number | null; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .fullJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "fullJoin", this.createJoin("full", false));
        /**
         * Executes a `cross join` operation by combining rows from two tables into a new table.
         *
         * Calling this method retrieves all rows from both main and joined tables, merging all rows from each table.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
         *
         * @param table the table to join.
         *
         * @example
         *
         * ```ts
         * // Select all users, each user with every pet
         * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
         *   .from(users)
         *   .crossJoin(pets)
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .crossJoin(pets)
         * ```
         */
        __publicField(this, "crossJoin", this.createJoin("cross", false));
        /**
         * Executes a `cross join lateral` operation by combining rows from two queries into a new table.
         *
         * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
         *
         * Calling this method retrieves all rows from both main and joined queries, merging all rows from each query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join-lateral}
         *
         * @param table the query to join.
         */
        __publicField(this, "crossJoinLateral", this.createJoin("cross", true));
        /**
         * Adds `union` set operator to the query.
         *
         * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
         *
         * @example
         *
         * ```ts
         * // Select all unique names from customers and users tables
         * await db.select({ name: users.name })
         *   .from(users)
         *   .union(
         *     db.select({ name: customers.name }).from(customers)
         *   );
         * // or
         * import { union } from 'drizzle-orm/pg-core'
         *
         * await union(
         *   db.select({ name: users.name }).from(users),
         *   db.select({ name: customers.name }).from(customers)
         * );
         * ```
         */
        __publicField(this, "union", this.createSetOperator("union", false));
        /**
         * Adds `union all` set operator to the query.
         *
         * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
         *
         * @example
         *
         * ```ts
         * // Select all transaction ids from both online and in-store sales
         * await db.select({ transaction: onlineSales.transactionId })
         *   .from(onlineSales)
         *   .unionAll(
         *     db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
         *   );
         * // or
         * import { unionAll } from 'drizzle-orm/pg-core'
         *
         * await unionAll(
         *   db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
         *   db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
         * );
         * ```
         */
        __publicField(this, "unionAll", this.createSetOperator("union", true));
        /**
         * Adds `intersect` set operator to the query.
         *
         * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
         *
         * @example
         *
         * ```ts
         * // Select course names that are offered in both departments A and B
         * await db.select({ courseName: depA.courseName })
         *   .from(depA)
         *   .intersect(
         *     db.select({ courseName: depB.courseName }).from(depB)
         *   );
         * // or
         * import { intersect } from 'drizzle-orm/pg-core'
         *
         * await intersect(
         *   db.select({ courseName: depA.courseName }).from(depA),
         *   db.select({ courseName: depB.courseName }).from(depB)
         * );
         * ```
         */
        __publicField(this, "intersect", this.createSetOperator("intersect", false));
        /**
         * Adds `intersect all` set operator to the query.
         *
         * Calling this method will retain only the rows that are present in both result sets including all duplicates.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}
         *
         * @example
         *
         * ```ts
         * // Select all products and quantities that are ordered by both regular and VIP customers
         * await db.select({
         *   productId: regularCustomerOrders.productId,
         *   quantityOrdered: regularCustomerOrders.quantityOrdered
         * })
         * .from(regularCustomerOrders)
         * .intersectAll(
         *   db.select({
         *     productId: vipCustomerOrders.productId,
         *     quantityOrdered: vipCustomerOrders.quantityOrdered
         *   })
         *   .from(vipCustomerOrders)
         * );
         * // or
         * import { intersectAll } from 'drizzle-orm/pg-core'
         *
         * await intersectAll(
         *   db.select({
         *     productId: regularCustomerOrders.productId,
         *     quantityOrdered: regularCustomerOrders.quantityOrdered
         *   })
         *   .from(regularCustomerOrders),
         *   db.select({
         *     productId: vipCustomerOrders.productId,
         *     quantityOrdered: vipCustomerOrders.quantityOrdered
         *   })
         *   .from(vipCustomerOrders)
         * );
         * ```
         */
        __publicField(this, "intersectAll", this.createSetOperator("intersect", true));
        /**
         * Adds `except` set operator to the query.
         *
         * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
         *
         * @example
         *
         * ```ts
         * // Select all courses offered in department A but not in department B
         * await db.select({ courseName: depA.courseName })
         *   .from(depA)
         *   .except(
         *     db.select({ courseName: depB.courseName }).from(depB)
         *   );
         * // or
         * import { except } from 'drizzle-orm/pg-core'
         *
         * await except(
         *   db.select({ courseName: depA.courseName }).from(depA),
         *   db.select({ courseName: depB.courseName }).from(depB)
         * );
         * ```
         */
        __publicField(this, "except", this.createSetOperator("except", false));
        /**
         * Adds `except all` set operator to the query.
         *
         * Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}
         *
         * @example
         *
         * ```ts
         * // Select all products that are ordered by regular customers but not by VIP customers
         * await db.select({
         *   productId: regularCustomerOrders.productId,
         *   quantityOrdered: regularCustomerOrders.quantityOrdered,
         * })
         * .from(regularCustomerOrders)
         * .exceptAll(
         *   db.select({
         *     productId: vipCustomerOrders.productId,
         *     quantityOrdered: vipCustomerOrders.quantityOrdered,
         *   })
         *   .from(vipCustomerOrders)
         * );
         * // or
         * import { exceptAll } from 'drizzle-orm/pg-core'
         *
         * await exceptAll(
         *   db.select({
         *     productId: regularCustomerOrders.productId,
         *     quantityOrdered: regularCustomerOrders.quantityOrdered
         *   })
         *   .from(regularCustomerOrders),
         *   db.select({
         *     productId: vipCustomerOrders.productId,
         *     quantityOrdered: vipCustomerOrders.quantityOrdered
         *   })
         *   .from(vipCustomerOrders)
         * );
         * ```
         */
        __publicField(this, "exceptAll", this.createSetOperator("except", true));
        this.config = {
          withList,
          table: table6,
          fields: { ...fields },
          distinct,
          setOperators: []
        };
        this.isPartialSelect = isPartialSelect;
        this.session = session;
        this.dialect = dialect6;
        this._ = {
          selectedFields: fields,
          config: this.config
        };
        this.tableName = getTableLikeName(table6);
        this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
        for (const item of extractUsedTable(table6)) this.usedTables.add(item);
      }
      /** @internal */
      getUsedTables() {
        return [...this.usedTables];
      }
      createJoin(joinType, lateral) {
        return (table6, on) => {
          const baseTableName = this.tableName;
          const tableName = getTableLikeName(table6);
          for (const item of extractUsedTable(table6)) this.usedTables.add(item);
          if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
            throw new Error(`Alias "${tableName}" is already used in this query`);
          }
          if (!this.isPartialSelect) {
            if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
              this.config.fields = {
                [baseTableName]: this.config.fields
              };
            }
            if (typeof tableName === "string" && !is(table6, SQL)) {
              const selection = is(table6, Subquery) ? table6._.selectedFields : is(table6, View3) ? table6[ViewBaseConfig].selectedFields : table6[Table2.Symbol.Columns];
              this.config.fields[tableName] = selection;
            }
          }
          if (typeof on === "function") {
            on = on(
              new Proxy(
                this.config.fields,
                new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
              )
            );
          }
          if (!this.config.joins) {
            this.config.joins = [];
          }
          this.config.joins.push({ on, table: table6, joinType, alias: tableName, lateral });
          if (typeof tableName === "string") {
            switch (joinType) {
              case "left": {
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
              case "right": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "cross":
              case "inner": {
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "full": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
            }
          }
          return this;
        };
      }
      createSetOperator(type, isAll) {
        return (rightSelection) => {
          const rightSelect = typeof rightSelection === "function" ? rightSelection(getPgSetOperators()) : rightSelection;
          if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {
            throw new Error(
              "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
            );
          }
          this.config.setOperators.push({ type, isAll, rightSelect });
          return this;
        };
      }
      /** @internal */
      addSetOperators(setOperators) {
        this.config.setOperators.push(...setOperators);
        return this;
      }
      /**
       * Adds a `where` clause to the query.
       *
       * Calling this method will select only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#filtering}
       *
       * @param where the `where` clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be selected.
       *
       * ```ts
       * // Select all cars with green color
       * await db.select().from(cars).where(eq(cars.color, 'green'));
       * // or
       * await db.select().from(cars).where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Select all BMW cars with a green color
       * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Select all cars with the green or blue color
       * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        if (typeof where === "function") {
          where = where(
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
            )
          );
        }
        this.config.where = where;
        return this;
      }
      /**
       * Adds a `having` clause to the query.
       *
       * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
       *
       * @param having the `having` clause.
       *
       * @example
       *
       * ```ts
       * // Select all brands with more than one car
       * await db.select({
       * 	brand: cars.brand,
       * 	count: sql<number>`cast(count(${cars.id}) as int)`,
       * })
       *   .from(cars)
       *   .groupBy(cars.brand)
       *   .having(({ count }) => gt(count, 1));
       * ```
       */
      having(having) {
        if (typeof having === "function") {
          having = having(
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
            )
          );
        }
        this.config.having = having;
        return this;
      }
      groupBy(...columns) {
        if (typeof columns[0] === "function") {
          const groupBy = columns[0](
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
        } else {
          this.config.groupBy = columns;
        }
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          if (this.config.setOperators.length > 0) {
            this.config.setOperators.at(-1).orderBy = orderByArray;
          } else {
            this.config.orderBy = orderByArray;
          }
        } else {
          const orderByArray = columns;
          if (this.config.setOperators.length > 0) {
            this.config.setOperators.at(-1).orderBy = orderByArray;
          } else {
            this.config.orderBy = orderByArray;
          }
        }
        return this;
      }
      /**
       * Adds a `limit` clause to the query.
       *
       * Calling this method will set the maximum number of rows that will be returned by this query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
       *
       * @param limit the `limit` clause.
       *
       * @example
       *
       * ```ts
       * // Get the first 10 people from this query.
       * await db.select().from(people).limit(10);
       * ```
       */
      limit(limit) {
        if (this.config.setOperators.length > 0) {
          this.config.setOperators.at(-1).limit = limit;
        } else {
          this.config.limit = limit;
        }
        return this;
      }
      /**
       * Adds an `offset` clause to the query.
       *
       * Calling this method will skip a number of rows when returning results from this query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
       *
       * @param offset the `offset` clause.
       *
       * @example
       *
       * ```ts
       * // Get the 10th-20th people from this query.
       * await db.select().from(people).offset(10).limit(10);
       * ```
       */
      offset(offset) {
        if (this.config.setOperators.length > 0) {
          this.config.setOperators.at(-1).offset = offset;
        } else {
          this.config.offset = offset;
        }
        return this;
      }
      /**
       * Adds a `for` clause to the query.
       *
       * Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried.
       *
       * See docs: {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE}
       *
       * @param strength the lock strength.
       * @param config the lock configuration.
       */
      for(strength, config = {}) {
        this.config.lockingClause = { strength, config };
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildSelectQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      as(alias) {
        const usedTables = [];
        usedTables.push(...extractUsedTable(this.config.table));
        if (this.config.joins) {
          for (const it of this.config.joins) usedTables.push(...extractUsedTable(it.table));
        }
        return new Proxy(
          new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]),
          new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
        );
      }
      /** @internal */
      getSelectedFields() {
        return new Proxy(
          this.config.fields,
          new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
        );
      }
      $dynamic() {
        return this;
      }
      $withCache(config) {
        this.cacheConfig = config === void 0 ? { config: {}, enable: true, autoInvalidate: true } : config === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config };
        return this;
      }
    };
    __publicField(PgSelectQueryBuilderBase, _a140, "PgSelectQueryBuilder");
    PgSelectBase = class extends (_b105 = PgSelectQueryBuilderBase, _a141 = entityKind, _b105) {
      constructor() {
        super(...arguments);
        __publicField(this, "authToken");
        __publicField(this, "execute", (placeholderValues) => {
          return tracer.startActiveSpan("drizzle.operation", () => {
            return this._prepare().execute(placeholderValues, this.authToken);
          });
        });
      }
      /** @internal */
      _prepare(name2) {
        const { session, config, dialect: dialect6, joinsNotNullableMap, authToken, cacheConfig, usedTables } = this;
        if (!session) {
          throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
        }
        const { fields } = config;
        return tracer.startActiveSpan("drizzle.prepareQuery", () => {
          const fieldsList = orderSelectedFields(fields);
          const query = session.prepareQuery(dialect6.sqlToQuery(this.getSQL()), fieldsList, name2, true, void 0, {
            type: "select",
            tables: [...usedTables]
          }, cacheConfig);
          query.joinsNotNullableMap = joinsNotNullableMap;
          return query.setToken(authToken);
        });
      }
      /**
       * Create a prepared statement for this query. This allows
       * the database to remember this query for the given session
       * and call it by name, rather than specifying the full query.
       *
       * {@link https://www.postgresql.org/docs/current/sql-prepare.html | Postgres prepare documentation}
       */
      prepare(name2) {
        return this._prepare(name2);
      }
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
    };
    __publicField(PgSelectBase, _a141, "PgSelect");
    applyMixins(PgSelectBase, [QueryPromise]);
    getPgSetOperators = () => ({
      union: union2,
      unionAll,
      intersect,
      intersectAll,
      except,
      exceptAll
    });
    union2 = createSetOperator("union", false);
    unionAll = createSetOperator("union", true);
    intersect = createSetOperator("intersect", false);
    intersectAll = createSetOperator("intersect", true);
    except = createSetOperator("except", false);
    exceptAll = createSetOperator("except", true);
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/query-builder.js
var _a142, QueryBuilder;
var init_query_builder2 = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/query-builder.js"() {
    "use strict";
    init_entity();
    init_dialect();
    init_selection_proxy();
    init_subquery();
    init_select2();
    _a142 = entityKind;
    QueryBuilder = class {
      constructor(dialect6) {
        __publicField(this, "dialect");
        __publicField(this, "dialectConfig");
        __publicField(this, "$with", (alias, selection) => {
          const queryBuilder = this;
          const as = (qb) => {
            if (typeof qb === "function") {
              qb = qb(queryBuilder);
            }
            return new Proxy(
              new WithSubquery(
                qb.getSQL(),
                selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
                alias,
                true
              ),
              new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
            );
          };
          return { as };
        });
        this.dialect = is(dialect6, PgDialect) ? dialect6 : void 0;
        this.dialectConfig = is(dialect6, PgDialect) ? void 0 : dialect6;
      }
      with(...queries) {
        const self2 = this;
        function select(fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self2.getDialect(),
            withList: queries
          });
        }
        function selectDistinct(fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self2.getDialect(),
            distinct: true
          });
        }
        function selectDistinctOn(on, fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self2.getDialect(),
            distinct: { on }
          });
        }
        return { select, selectDistinct, selectDistinctOn };
      }
      select(fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: void 0,
          dialect: this.getDialect()
        });
      }
      selectDistinct(fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: void 0,
          dialect: this.getDialect(),
          distinct: true
        });
      }
      selectDistinctOn(on, fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: void 0,
          dialect: this.getDialect(),
          distinct: { on }
        });
      }
      // Lazy load dialect to avoid circular dependency
      getDialect() {
        if (!this.dialect) {
          this.dialect = new PgDialect(this.dialectConfig);
        }
        return this.dialect;
      }
    };
    __publicField(QueryBuilder, _a142, "PgQueryBuilder");
  }
});

// ../drizzle-orm/dist/pg-core/view.js
function pgViewWithSchema(name2, selection, schema5) {
  if (selection) {
    return new ManualViewBuilder(name2, selection, schema5);
  }
  return new ViewBuilder(name2, schema5);
}
function pgMaterializedViewWithSchema(name2, selection, schema5) {
  if (selection) {
    return new ManualMaterializedViewBuilder(name2, selection, schema5);
  }
  return new MaterializedViewBuilder(name2, schema5);
}
function isPgView(obj) {
  return is(obj, PgView2);
}
function isPgMaterializedView(obj) {
  return is(obj, PgMaterializedView);
}
var _a143, DefaultViewBuilderCore, _a144, _b106, ViewBuilder, _a145, _b107, ManualViewBuilder, _a146, MaterializedViewBuilderCore, _a147, _b108, MaterializedViewBuilder, _a148, _b109, ManualMaterializedViewBuilder, _a149, _b110, _c4, PgView2, PgMaterializedViewConfig, _a150, _b111, _c5, PgMaterializedView;
var init_view = __esm({
  "../drizzle-orm/dist/pg-core/view.js"() {
    "use strict";
    init_entity();
    init_selection_proxy();
    init_utils2();
    init_query_builder2();
    init_table2();
    init_view_base();
    init_view_common2();
    _a143 = entityKind;
    DefaultViewBuilderCore = class {
      constructor(name2, schema5) {
        __publicField(this, "config", {});
        this.name = name2;
        this.schema = schema5;
      }
      with(config) {
        this.config.with = config;
        return this;
      }
    };
    __publicField(DefaultViewBuilderCore, _a143, "PgDefaultViewBuilderCore");
    ViewBuilder = class extends (_b106 = DefaultViewBuilderCore, _a144 = entityKind, _b106) {
      as(qb) {
        if (typeof qb === "function") {
          qb = qb(new QueryBuilder());
        }
        const selectionProxy = new SelectionProxyHandler({
          alias: this.name,
          sqlBehavior: "error",
          sqlAliasedBehavior: "alias",
          replaceOriginalName: true
        });
        const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
        return new Proxy(
          new PgView2({
            pgConfig: this.config,
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: aliasedSelection,
              query: qb.getSQL().inlineParams()
            }
          }),
          selectionProxy
        );
      }
    };
    __publicField(ViewBuilder, _a144, "PgViewBuilder");
    ManualViewBuilder = class extends (_b107 = DefaultViewBuilderCore, _a145 = entityKind, _b107) {
      constructor(name2, columns, schema5) {
        super(name2, schema5);
        __publicField(this, "columns");
        this.columns = getTableColumns(pgTable(name2, columns));
      }
      existing() {
        return new Proxy(
          new PgView2({
            pgConfig: void 0,
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: this.columns,
              query: void 0
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
      as(query) {
        return new Proxy(
          new PgView2({
            pgConfig: this.config,
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: this.columns,
              query: query.inlineParams()
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
    };
    __publicField(ManualViewBuilder, _a145, "PgManualViewBuilder");
    _a146 = entityKind;
    MaterializedViewBuilderCore = class {
      constructor(name2, schema5) {
        __publicField(this, "config", {});
        this.name = name2;
        this.schema = schema5;
      }
      using(using) {
        this.config.using = using;
        return this;
      }
      with(config) {
        this.config.with = config;
        return this;
      }
      tablespace(tablespace) {
        this.config.tablespace = tablespace;
        return this;
      }
      withNoData() {
        this.config.withNoData = true;
        return this;
      }
    };
    __publicField(MaterializedViewBuilderCore, _a146, "PgMaterializedViewBuilderCore");
    MaterializedViewBuilder = class extends (_b108 = MaterializedViewBuilderCore, _a147 = entityKind, _b108) {
      as(qb) {
        if (typeof qb === "function") {
          qb = qb(new QueryBuilder());
        }
        const selectionProxy = new SelectionProxyHandler({
          alias: this.name,
          sqlBehavior: "error",
          sqlAliasedBehavior: "alias",
          replaceOriginalName: true
        });
        const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
        return new Proxy(
          new PgMaterializedView({
            pgConfig: {
              with: this.config.with,
              using: this.config.using,
              tablespace: this.config.tablespace,
              withNoData: this.config.withNoData
            },
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: aliasedSelection,
              query: qb.getSQL().inlineParams()
            }
          }),
          selectionProxy
        );
      }
    };
    __publicField(MaterializedViewBuilder, _a147, "PgMaterializedViewBuilder");
    ManualMaterializedViewBuilder = class extends (_b109 = MaterializedViewBuilderCore, _a148 = entityKind, _b109) {
      constructor(name2, columns, schema5) {
        super(name2, schema5);
        __publicField(this, "columns");
        this.columns = getTableColumns(pgTable(name2, columns));
      }
      existing() {
        return new Proxy(
          new PgMaterializedView({
            pgConfig: {
              tablespace: this.config.tablespace,
              using: this.config.using,
              with: this.config.with,
              withNoData: this.config.withNoData
            },
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: this.columns,
              query: void 0
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
      as(query) {
        return new Proxy(
          new PgMaterializedView({
            pgConfig: {
              tablespace: this.config.tablespace,
              using: this.config.using,
              with: this.config.with,
              withNoData: this.config.withNoData
            },
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: this.columns,
              query: query.inlineParams()
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
    };
    __publicField(ManualMaterializedViewBuilder, _a148, "PgManualMaterializedViewBuilder");
    PgView2 = class extends (_c4 = PgViewBase, _b110 = entityKind, _a149 = PgViewConfig, _c4) {
      constructor({ pgConfig, config }) {
        super(config);
        __publicField(this, _a149);
        if (pgConfig) {
          this[PgViewConfig] = {
            with: pgConfig.with
          };
        }
      }
    };
    __publicField(PgView2, _b110, "PgView");
    PgMaterializedViewConfig = Symbol.for("drizzle:PgMaterializedViewConfig");
    PgMaterializedView = class extends (_c5 = PgViewBase, _b111 = entityKind, _a150 = PgMaterializedViewConfig, _c5) {
      constructor({ pgConfig, config }) {
        super(config);
        __publicField(this, _a150);
        this[PgMaterializedViewConfig] = {
          with: pgConfig?.with,
          using: pgConfig?.using,
          tablespace: pgConfig?.tablespace,
          withNoData: pgConfig?.withNoData
        };
      }
    };
    __publicField(PgMaterializedView, _b111, "PgMaterializedView");
  }
});

// ../drizzle-orm/dist/pg-core/utils.js
function getTableConfig(table6) {
  const columns = Object.values(table6[Table2.Symbol.Columns]);
  const indexes = [];
  const checks = [];
  const primaryKeys = [];
  const foreignKeys = Object.values(table6[PgTable.Symbol.InlineForeignKeys]);
  const uniqueConstraints = [];
  const name2 = table6[Table2.Symbol.Name];
  const schema5 = table6[Table2.Symbol.Schema];
  const policies = [];
  const enableRLS = table6[PgTable.Symbol.EnableRLS];
  const extraConfigBuilder = table6[PgTable.Symbol.ExtraConfigBuilder];
  if (extraConfigBuilder !== void 0) {
    const extraConfig = extraConfigBuilder(table6[Table2.Symbol.ExtraConfigColumns]);
    const extraValues = Array.isArray(extraConfig) ? extraConfig.flat(1) : Object.values(extraConfig);
    for (const builder of extraValues) {
      if (is(builder, IndexBuilder)) {
        indexes.push(builder.build(table6));
      } else if (is(builder, CheckBuilder)) {
        checks.push(builder.build(table6));
      } else if (is(builder, UniqueConstraintBuilder)) {
        uniqueConstraints.push(builder.build(table6));
      } else if (is(builder, PrimaryKeyBuilder)) {
        primaryKeys.push(builder.build(table6));
      } else if (is(builder, ForeignKeyBuilder)) {
        foreignKeys.push(builder.build(table6));
      } else if (is(builder, PgPolicy)) {
        policies.push(builder);
      }
    }
  }
  return {
    columns,
    indexes,
    foreignKeys,
    checks,
    primaryKeys,
    uniqueConstraints,
    name: name2,
    schema: schema5,
    policies,
    enableRLS
  };
}
function extractUsedTable(table6) {
  if (is(table6, PgTable)) {
    return [table6[Schema] ? `${table6[Schema]}.${table6[Table2.Symbol.BaseName]}` : table6[Table2.Symbol.BaseName]];
  }
  if (is(table6, Subquery)) {
    return table6._.usedTables ?? [];
  }
  if (is(table6, SQL)) {
    return table6.usedTables ?? [];
  }
  return [];
}
function getViewConfig(view5) {
  return {
    ...view5[ViewBaseConfig],
    ...view5[PgViewConfig]
  };
}
function getMaterializedViewConfig(view5) {
  return {
    ...view5[ViewBaseConfig],
    ...view5[PgMaterializedViewConfig]
  };
}
var init_utils4 = __esm({
  "../drizzle-orm/dist/pg-core/utils.js"() {
    "use strict";
    init_entity();
    init_table2();
    init_sql();
    init_subquery();
    init_table();
    init_view_common();
    init_checks();
    init_foreign_keys();
    init_indexes();
    init_policies();
    init_primary_keys();
    init_unique_constraint();
    init_view_common2();
    init_view();
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/delete.js
var _a151, _b112, PgDeleteBase;
var init_delete = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/delete.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_selection_proxy();
    init_table();
    init_tracing();
    init_utils2();
    init_utils4();
    PgDeleteBase = class extends (_b112 = QueryPromise, _a151 = entityKind, _b112) {
      constructor(table6, session, dialect6, withList) {
        super();
        __publicField(this, "config");
        __publicField(this, "cacheConfig");
        __publicField(this, "authToken");
        __publicField(this, "execute", (placeholderValues) => {
          return tracer.startActiveSpan("drizzle.operation", () => {
            return this._prepare().execute(placeholderValues, this.authToken);
          });
        });
        this.session = session;
        this.dialect = dialect6;
        this.config = { table: table6, withList };
      }
      /**
       * Adds a `where` clause to the query.
       *
       * Calling this method will delete only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/delete}
       *
       * @param where the `where` clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be deleted.
       *
       * ```ts
       * // Delete all cars with green color
       * await db.delete(cars).where(eq(cars.color, 'green'));
       * // or
       * await db.delete(cars).where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Delete all BMW cars with a green color
       * await db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Delete all cars with the green or blue color
       * await db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        this.config.where = where;
        return this;
      }
      returning(fields = this.config.table[Table2.Symbol.Columns]) {
        this.config.returningFields = fields;
        this.config.returning = orderSelectedFields(fields);
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildDeleteQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(name2) {
        return tracer.startActiveSpan("drizzle.prepareQuery", () => {
          return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name2, true, void 0, {
            type: "delete",
            tables: extractUsedTable(this.config.table)
          }, this.cacheConfig);
        });
      }
      prepare(name2) {
        return this._prepare(name2);
      }
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
      /** @internal */
      getSelectedFields() {
        return this.config.returningFields ? new Proxy(
          this.config.returningFields,
          new SelectionProxyHandler({
            alias: getTableName(this.config.table),
            sqlAliasedBehavior: "alias",
            sqlBehavior: "error"
          })
        ) : void 0;
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(PgDeleteBase, _a151, "PgDelete");
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/insert.js
var _a152, PgInsertBuilder, _a153, _b113, PgInsertBase;
var init_insert = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/insert.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_selection_proxy();
    init_sql();
    init_table();
    init_tracing();
    init_utils2();
    init_utils4();
    init_query_builder2();
    _a152 = entityKind;
    PgInsertBuilder = class {
      constructor(table6, session, dialect6, withList, overridingSystemValue_) {
        __publicField(this, "authToken");
        this.table = table6;
        this.session = session;
        this.dialect = dialect6;
        this.withList = withList;
        this.overridingSystemValue_ = overridingSystemValue_;
      }
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
      overridingSystemValue() {
        this.overridingSystemValue_ = true;
        return this;
      }
      values(values) {
        values = Array.isArray(values) ? values : [values];
        if (values.length === 0) {
          throw new Error("values() must be called with at least one value");
        }
        const mappedValues = values.map((entry) => {
          const result = {};
          const cols = this.table[Table2.Symbol.Columns];
          for (const colKey of Object.keys(entry)) {
            const colValue = entry[colKey];
            result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
          }
          return result;
        });
        return new PgInsertBase(
          this.table,
          mappedValues,
          this.session,
          this.dialect,
          this.withList,
          false,
          this.overridingSystemValue_
        ).setToken(this.authToken);
      }
      select(selectQuery) {
        const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder()) : selectQuery;
        if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) {
          throw new Error(
            "Insert select error: selected fields are not the same or are in a different order compared to the table definition"
          );
        }
        return new PgInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
      }
    };
    __publicField(PgInsertBuilder, _a152, "PgInsertBuilder");
    PgInsertBase = class extends (_b113 = QueryPromise, _a153 = entityKind, _b113) {
      constructor(table6, values, session, dialect6, withList, select, overridingSystemValue_) {
        super();
        __publicField(this, "config");
        __publicField(this, "cacheConfig");
        __publicField(this, "authToken");
        __publicField(this, "execute", (placeholderValues) => {
          return tracer.startActiveSpan("drizzle.operation", () => {
            return this._prepare().execute(placeholderValues, this.authToken);
          });
        });
        this.session = session;
        this.dialect = dialect6;
        this.config = { table: table6, values, withList, select, overridingSystemValue_ };
      }
      returning(fields = this.config.table[Table2.Symbol.Columns]) {
        this.config.returningFields = fields;
        this.config.returning = orderSelectedFields(fields);
        return this;
      }
      /**
       * Adds an `on conflict do nothing` clause to the query.
       *
       * Calling this method simply avoids inserting a row as its alternative action.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
       *
       * @param config The `target` and `where` clauses.
       *
       * @example
       * ```ts
       * // Insert one row and cancel the insert if there's a conflict
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoNothing();
       *
       * // Explicitly specify conflict target
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoNothing({ target: cars.id });
       * ```
       */
      onConflictDoNothing(config = {}) {
        if (config.target === void 0) {
          this.config.onConflict = sql`do nothing`;
        } else {
          let targetColumn = "";
          targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
          const whereSql = config.where ? sql` where ${config.where}` : void 0;
          this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`;
        }
        return this;
      }
      /**
       * Adds an `on conflict do update` clause to the query.
       *
       * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
       *
       * @param config The `target`, `set` and `where` clauses.
       *
       * @example
       * ```ts
       * // Update the row if there's a conflict
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoUpdate({
       *     target: cars.id,
       *     set: { brand: 'Porsche' }
       *   });
       *
       * // Upsert with 'where' clause
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoUpdate({
       *     target: cars.id,
       *     set: { brand: 'newBMW' },
       *     targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`,
       *   });
       * ```
       */
      onConflictDoUpdate(config) {
        if (config.where && (config.targetWhere || config.setWhere)) {
          throw new Error(
            'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'
          );
        }
        const whereSql = config.where ? sql` where ${config.where}` : void 0;
        const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
        const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
        const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
        let targetColumn = "";
        targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target));
        this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildInsertQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(name2) {
        return tracer.startActiveSpan("drizzle.prepareQuery", () => {
          return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name2, true, void 0, {
            type: "insert",
            tables: extractUsedTable(this.config.table)
          }, this.cacheConfig);
        });
      }
      prepare(name2) {
        return this._prepare(name2);
      }
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
      /** @internal */
      getSelectedFields() {
        return this.config.returningFields ? new Proxy(
          this.config.returningFields,
          new SelectionProxyHandler({
            alias: getTableName(this.config.table),
            sqlAliasedBehavior: "alias",
            sqlBehavior: "error"
          })
        ) : void 0;
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(PgInsertBase, _a153, "PgInsert");
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/refresh-materialized-view.js
var _a154, _b114, PgRefreshMaterializedView;
var init_refresh_materialized_view = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/refresh-materialized-view.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_tracing();
    PgRefreshMaterializedView = class extends (_b114 = QueryPromise, _a154 = entityKind, _b114) {
      constructor(view5, session, dialect6) {
        super();
        __publicField(this, "config");
        __publicField(this, "authToken");
        __publicField(this, "execute", (placeholderValues) => {
          return tracer.startActiveSpan("drizzle.operation", () => {
            return this._prepare().execute(placeholderValues, this.authToken);
          });
        });
        this.session = session;
        this.dialect = dialect6;
        this.config = { view: view5 };
      }
      concurrently() {
        if (this.config.withNoData !== void 0) {
          throw new Error("Cannot use concurrently and withNoData together");
        }
        this.config.concurrently = true;
        return this;
      }
      withNoData() {
        if (this.config.concurrently !== void 0) {
          throw new Error("Cannot use concurrently and withNoData together");
        }
        this.config.withNoData = true;
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildRefreshMaterializedViewQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(name2) {
        return tracer.startActiveSpan("drizzle.prepareQuery", () => {
          return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), void 0, name2, true);
        });
      }
      prepare(name2) {
        return this._prepare(name2);
      }
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
    };
    __publicField(PgRefreshMaterializedView, _a154, "PgRefreshMaterializedView");
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/select.types.js
var init_select_types = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/select.types.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/update.js
var _a155, PgUpdateBuilder, _a156, _b115, PgUpdateBase;
var init_update = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/update.js"() {
    "use strict";
    init_entity();
    init_table2();
    init_query_promise();
    init_selection_proxy();
    init_sql();
    init_subquery();
    init_table();
    init_utils2();
    init_view_common();
    init_utils4();
    _a155 = entityKind;
    PgUpdateBuilder = class {
      constructor(table6, session, dialect6, withList) {
        __publicField(this, "authToken");
        this.table = table6;
        this.session = session;
        this.dialect = dialect6;
        this.withList = withList;
      }
      setToken(token) {
        this.authToken = token;
        return this;
      }
      set(values) {
        return new PgUpdateBase(
          this.table,
          mapUpdateSet(this.table, values),
          this.session,
          this.dialect,
          this.withList
        ).setToken(this.authToken);
      }
    };
    __publicField(PgUpdateBuilder, _a155, "PgUpdateBuilder");
    PgUpdateBase = class extends (_b115 = QueryPromise, _a156 = entityKind, _b115) {
      constructor(table6, set, session, dialect6, withList) {
        super();
        __publicField(this, "config");
        __publicField(this, "tableName");
        __publicField(this, "joinsNotNullableMap");
        __publicField(this, "cacheConfig");
        __publicField(this, "leftJoin", this.createJoin("left"));
        __publicField(this, "rightJoin", this.createJoin("right"));
        __publicField(this, "innerJoin", this.createJoin("inner"));
        __publicField(this, "fullJoin", this.createJoin("full"));
        __publicField(this, "authToken");
        __publicField(this, "execute", (placeholderValues) => {
          return this._prepare().execute(placeholderValues, this.authToken);
        });
        this.session = session;
        this.dialect = dialect6;
        this.config = { set, table: table6, withList, joins: [] };
        this.tableName = getTableLikeName(table6);
        this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
      }
      from(source) {
        const src = source;
        const tableName = getTableLikeName(src);
        if (typeof tableName === "string") {
          this.joinsNotNullableMap[tableName] = true;
        }
        this.config.from = src;
        return this;
      }
      getTableLikeFields(table6) {
        if (is(table6, PgTable)) {
          return table6[Table2.Symbol.Columns];
        } else if (is(table6, Subquery)) {
          return table6._.selectedFields;
        }
        return table6[ViewBaseConfig].selectedFields;
      }
      createJoin(joinType) {
        return (table6, on) => {
          const tableName = getTableLikeName(table6);
          if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) {
            throw new Error(`Alias "${tableName}" is already used in this query`);
          }
          if (typeof on === "function") {
            const from = this.config.from && !is(this.config.from, SQL) ? this.getTableLikeFields(this.config.from) : void 0;
            on = on(
              new Proxy(
                this.config.table[Table2.Symbol.Columns],
                new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
              ),
              from && new Proxy(
                from,
                new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
              )
            );
          }
          this.config.joins.push({ on, table: table6, joinType, alias: tableName });
          if (typeof tableName === "string") {
            switch (joinType) {
              case "left": {
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
              case "right": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "inner": {
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "full": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
            }
          }
          return this;
        };
      }
      /**
       * Adds a 'where' clause to the query.
       *
       * Calling this method will update only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/update}
       *
       * @param where the 'where' clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be updated.
       *
       * ```ts
       * // Update all cars with green color
       * await db.update(cars).set({ color: 'red' })
       *   .where(eq(cars.color, 'green'));
       * // or
       * await db.update(cars).set({ color: 'red' })
       *   .where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Update all BMW cars with a green color
       * await db.update(cars).set({ color: 'red' })
       *   .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Update all cars with the green or blue color
       * await db.update(cars).set({ color: 'red' })
       *   .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        this.config.where = where;
        return this;
      }
      returning(fields) {
        if (!fields) {
          fields = Object.assign({}, this.config.table[Table2.Symbol.Columns]);
          if (this.config.from) {
            const tableName = getTableLikeName(this.config.from);
            if (typeof tableName === "string" && this.config.from && !is(this.config.from, SQL)) {
              const fromFields = this.getTableLikeFields(this.config.from);
              fields[tableName] = fromFields;
            }
            for (const join of this.config.joins) {
              const tableName2 = getTableLikeName(join.table);
              if (typeof tableName2 === "string" && !is(join.table, SQL)) {
                const fromFields = this.getTableLikeFields(join.table);
                fields[tableName2] = fromFields;
              }
            }
          }
        }
        this.config.returningFields = fields;
        this.config.returning = orderSelectedFields(fields);
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildUpdateQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(name2) {
        const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name2, true, void 0, {
          type: "insert",
          tables: extractUsedTable(this.config.table)
        }, this.cacheConfig);
        query.joinsNotNullableMap = this.joinsNotNullableMap;
        return query;
      }
      prepare(name2) {
        return this._prepare(name2);
      }
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
      /** @internal */
      getSelectedFields() {
        return this.config.returningFields ? new Proxy(
          this.config.returningFields,
          new SelectionProxyHandler({
            alias: getTableName(this.config.table),
            sqlAliasedBehavior: "alias",
            sqlBehavior: "error"
          })
        ) : void 0;
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(PgUpdateBase, _a156, "PgUpdate");
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/index.js
var init_query_builders = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/index.js"() {
    "use strict";
    init_delete();
    init_insert();
    init_query_builder2();
    init_refresh_materialized_view();
    init_select2();
    init_select_types();
    init_update();
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/count.js
var _a157, _b116, _c6, _PgCountBuilder, PgCountBuilder;
var init_count = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/count.js"() {
    "use strict";
    init_entity();
    init_sql();
    _PgCountBuilder = class _PgCountBuilder extends (_c6 = SQL, _b116 = entityKind, _a157 = Symbol.toStringTag, _c6) {
      constructor(params) {
        super(_PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
        __publicField(this, "sql");
        __publicField(this, "token");
        __publicField(this, _a157, "PgCountBuilder");
        __publicField(this, "session");
        this.params = params;
        this.mapWith(Number);
        this.session = params.session;
        this.sql = _PgCountBuilder.buildCount(
          params.source,
          params.filters
        );
      }
      static buildEmbeddedCount(source, filters) {
        return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
      }
      static buildCount(source, filters) {
        return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters};`;
      }
      /** @intrnal */
      setToken(token) {
        this.token = token;
        return this;
      }
      then(onfulfilled, onrejected) {
        return Promise.resolve(this.session.count(this.sql, this.token)).then(
          onfulfilled,
          onrejected
        );
      }
      catch(onRejected) {
        return this.then(void 0, onRejected);
      }
      finally(onFinally) {
        return this.then(
          (value) => {
            onFinally?.();
            return value;
          },
          (reason) => {
            onFinally?.();
            throw reason;
          }
        );
      }
    };
    __publicField(_PgCountBuilder, _b116, "PgCountBuilder");
    PgCountBuilder = _PgCountBuilder;
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/query.js
var _a158, RelationalQueryBuilder, _a159, _b117, PgRelationalQuery;
var init_query = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/query.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_relations();
    init_tracing();
    _a158 = entityKind;
    RelationalQueryBuilder = class {
      constructor(fullSchema, schema5, tableNamesMap, table6, tableConfig, dialect6, session) {
        this.fullSchema = fullSchema;
        this.schema = schema5;
        this.tableNamesMap = tableNamesMap;
        this.table = table6;
        this.tableConfig = tableConfig;
        this.dialect = dialect6;
        this.session = session;
      }
      findMany(config) {
        return new PgRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config ? config : {},
          "many"
        );
      }
      findFirst(config) {
        return new PgRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config ? { ...config, limit: 1 } : { limit: 1 },
          "first"
        );
      }
    };
    __publicField(RelationalQueryBuilder, _a158, "PgRelationalQueryBuilder");
    PgRelationalQuery = class extends (_b117 = QueryPromise, _a159 = entityKind, _b117) {
      constructor(fullSchema, schema5, tableNamesMap, table6, tableConfig, dialect6, session, config, mode) {
        super();
        __publicField(this, "authToken");
        this.fullSchema = fullSchema;
        this.schema = schema5;
        this.tableNamesMap = tableNamesMap;
        this.table = table6;
        this.tableConfig = tableConfig;
        this.dialect = dialect6;
        this.session = session;
        this.config = config;
        this.mode = mode;
      }
      /** @internal */
      _prepare(name2) {
        return tracer.startActiveSpan("drizzle.prepareQuery", () => {
          const { query, builtQuery } = this._toSQL();
          return this.session.prepareQuery(
            builtQuery,
            void 0,
            name2,
            true,
            (rawRows, mapColumnValue) => {
              const rows = rawRows.map(
                (row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)
              );
              if (this.mode === "first") {
                return rows[0];
              }
              return rows;
            }
          );
        });
      }
      prepare(name2) {
        return this._prepare(name2);
      }
      _getQuery() {
        return this.dialect.buildRelationalQueryWithoutPK({
          fullSchema: this.fullSchema,
          schema: this.schema,
          tableNamesMap: this.tableNamesMap,
          table: this.table,
          tableConfig: this.tableConfig,
          queryConfig: this.config,
          tableAlias: this.tableConfig.tsName
        });
      }
      /** @internal */
      getSQL() {
        return this._getQuery().sql;
      }
      _toSQL() {
        const query = this._getQuery();
        const builtQuery = this.dialect.sqlToQuery(query.sql);
        return { query, builtQuery };
      }
      toSQL() {
        return this._toSQL().builtQuery;
      }
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
      execute() {
        return tracer.startActiveSpan("drizzle.operation", () => {
          return this._prepare().execute(void 0, this.authToken);
        });
      }
    };
    __publicField(PgRelationalQuery, _a159, "PgRelationalQuery");
  }
});

// ../drizzle-orm/dist/pg-core/query-builders/raw.js
var _a160, _b118, PgRaw;
var init_raw = __esm({
  "../drizzle-orm/dist/pg-core/query-builders/raw.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    PgRaw = class extends (_b118 = QueryPromise, _a160 = entityKind, _b118) {
      constructor(execute, sql2, query, mapBatchResult) {
        super();
        this.execute = execute;
        this.sql = sql2;
        this.query = query;
        this.mapBatchResult = mapBatchResult;
      }
      /** @internal */
      getSQL() {
        return this.sql;
      }
      getQuery() {
        return this.query;
      }
      mapResult(result, isFromBatch) {
        return isFromBatch ? this.mapBatchResult(result) : result;
      }
      _prepare() {
        return this;
      }
      /** @internal */
      isResponseInArrayMode() {
        return false;
      }
    };
    __publicField(PgRaw, _a160, "PgRaw");
  }
});

// ../drizzle-orm/dist/pg-core/db.js
var _a161, PgDatabase;
var init_db = __esm({
  "../drizzle-orm/dist/pg-core/db.js"() {
    "use strict";
    init_entity();
    init_query_builders();
    init_selection_proxy();
    init_sql();
    init_subquery();
    init_count();
    init_query();
    init_raw();
    init_refresh_materialized_view();
    _a161 = entityKind;
    PgDatabase = class {
      constructor(dialect6, session, schema5) {
        __publicField(this, "query");
        /**
         * Creates a subquery that defines a temporary named result set as a CTE.
         *
         * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
         *
         * @param alias The alias for the subquery.
         *
         * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
         *
         * @example
         *
         * ```ts
         * // Create a subquery with alias 'sq' and use it in the select query
         * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
         *
         * const result = await db.with(sq).select().from(sq);
         * ```
         *
         * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
         *
         * ```ts
         * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
         * const sq = db.$with('sq').as(db.select({
         *   name: sql<string>`upper(${users.name})`.as('name'),
         * })
         * .from(users));
         *
         * const result = await db.with(sq).select({ name: sq.name }).from(sq);
         * ```
         */
        __publicField(this, "$with", (alias, selection) => {
          const self2 = this;
          const as = (qb) => {
            if (typeof qb === "function") {
              qb = qb(new QueryBuilder(self2.dialect));
            }
            return new Proxy(
              new WithSubquery(
                qb.getSQL(),
                selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
                alias,
                true
              ),
              new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
            );
          };
          return { as };
        });
        __publicField(this, "$cache");
        __publicField(this, "authToken");
        this.dialect = dialect6;
        this.session = session;
        this._ = schema5 ? {
          schema: schema5.schema,
          fullSchema: schema5.fullSchema,
          tableNamesMap: schema5.tableNamesMap,
          session
        } : {
          schema: void 0,
          fullSchema: {},
          tableNamesMap: {},
          session
        };
        this.query = {};
        if (this._.schema) {
          for (const [tableName, columns] of Object.entries(this._.schema)) {
            this.query[tableName] = new RelationalQueryBuilder(
              schema5.fullSchema,
              this._.schema,
              this._.tableNamesMap,
              schema5.fullSchema[tableName],
              columns,
              dialect6,
              session
            );
          }
        }
        this.$cache = { invalidate: async (_params) => {
        } };
      }
      $count(source, filters) {
        return new PgCountBuilder({ source, filters, session: this.session });
      }
      /**
       * Incorporates a previously defined CTE (using `$with`) into the main query.
       *
       * This method allows the main query to reference a temporary named result set.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
       *
       * @param queries The CTEs to incorporate into the main query.
       *
       * @example
       *
       * ```ts
       * // Define a subquery 'sq' as a CTE using $with
       * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
       *
       * // Incorporate the CTE 'sq' into the main query and select from it
       * const result = await db.with(sq).select().from(sq);
       * ```
       */
      with(...queries) {
        const self2 = this;
        function select(fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: self2.session,
            dialect: self2.dialect,
            withList: queries
          });
        }
        function selectDistinct(fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: self2.session,
            dialect: self2.dialect,
            withList: queries,
            distinct: true
          });
        }
        function selectDistinctOn(on, fields) {
          return new PgSelectBuilder({
            fields: fields ?? void 0,
            session: self2.session,
            dialect: self2.dialect,
            withList: queries,
            distinct: { on }
          });
        }
        function update(table6) {
          return new PgUpdateBuilder(table6, self2.session, self2.dialect, queries);
        }
        function insert(table6) {
          return new PgInsertBuilder(table6, self2.session, self2.dialect, queries);
        }
        function delete_(table6) {
          return new PgDeleteBase(table6, self2.session, self2.dialect, queries);
        }
        return { select, selectDistinct, selectDistinctOn, update, insert, delete: delete_ };
      }
      select(fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: this.session,
          dialect: this.dialect
        });
      }
      selectDistinct(fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: this.session,
          dialect: this.dialect,
          distinct: true
        });
      }
      selectDistinctOn(on, fields) {
        return new PgSelectBuilder({
          fields: fields ?? void 0,
          session: this.session,
          dialect: this.dialect,
          distinct: { on }
        });
      }
      /**
       * Creates an update query.
       *
       * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
       *
       * Use `.set()` method to specify which values to update.
       *
       * See docs: {@link https://orm.drizzle.team/docs/update}
       *
       * @param table The table to update.
       *
       * @example
       *
       * ```ts
       * // Update all rows in the 'cars' table
       * await db.update(cars).set({ color: 'red' });
       *
       * // Update rows with filters and conditions
       * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
       *
       * // Update with returning clause
       * const updatedCar: Car[] = await db.update(cars)
       *   .set({ color: 'red' })
       *   .where(eq(cars.id, 1))
       *   .returning();
       * ```
       */
      update(table6) {
        return new PgUpdateBuilder(table6, this.session, this.dialect);
      }
      /**
       * Creates an insert query.
       *
       * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert}
       *
       * @param table The table to insert into.
       *
       * @example
       *
       * ```ts
       * // Insert one row
       * await db.insert(cars).values({ brand: 'BMW' });
       *
       * // Insert multiple rows
       * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
       *
       * // Insert with returning clause
       * const insertedCar: Car[] = await db.insert(cars)
       *   .values({ brand: 'BMW' })
       *   .returning();
       * ```
       */
      insert(table6) {
        return new PgInsertBuilder(table6, this.session, this.dialect);
      }
      /**
       * Creates a delete query.
       *
       * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
       *
       * See docs: {@link https://orm.drizzle.team/docs/delete}
       *
       * @param table The table to delete from.
       *
       * @example
       *
       * ```ts
       * // Delete all rows in the 'cars' table
       * await db.delete(cars);
       *
       * // Delete rows with filters and conditions
       * await db.delete(cars).where(eq(cars.color, 'green'));
       *
       * // Delete with returning clause
       * const deletedCar: Car[] = await db.delete(cars)
       *   .where(eq(cars.id, 1))
       *   .returning();
       * ```
       */
      delete(table6) {
        return new PgDeleteBase(table6, this.session, this.dialect);
      }
      refreshMaterializedView(view5) {
        return new PgRefreshMaterializedView(view5, this.session, this.dialect);
      }
      execute(query) {
        const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
        const builtQuery = this.dialect.sqlToQuery(sequel);
        const prepared = this.session.prepareQuery(
          builtQuery,
          void 0,
          void 0,
          false
        );
        return new PgRaw(
          () => prepared.execute(void 0, this.authToken),
          sequel,
          builtQuery,
          (result) => prepared.mapResult(result, true)
        );
      }
      transaction(transaction, config) {
        return this.session.transaction(transaction, config);
      }
    };
    __publicField(PgDatabase, _a161, "PgDatabase");
  }
});

// ../drizzle-orm/dist/pg-core/roles.js
var _a162, PgRole;
var init_roles = __esm({
  "../drizzle-orm/dist/pg-core/roles.js"() {
    "use strict";
    init_entity();
    _a162 = entityKind;
    PgRole = class {
      constructor(name2, config) {
        /** @internal */
        __publicField(this, "_existing");
        /** @internal */
        __publicField(this, "createDb");
        /** @internal */
        __publicField(this, "createRole");
        /** @internal */
        __publicField(this, "inherit");
        this.name = name2;
        if (config) {
          this.createDb = config.createDb;
          this.createRole = config.createRole;
          this.inherit = config.inherit;
        }
      }
      existing() {
        this._existing = true;
        return this;
      }
    };
    __publicField(PgRole, _a162, "PgRole");
  }
});

// ../drizzle-orm/dist/pg-core/sequence.js
function pgSequenceWithSchema(name2, options, schema5) {
  return new PgSequence(name2, options, schema5);
}
function isPgSequence(obj) {
  return is(obj, PgSequence);
}
var _a163, PgSequence;
var init_sequence = __esm({
  "../drizzle-orm/dist/pg-core/sequence.js"() {
    "use strict";
    init_entity();
    _a163 = entityKind;
    PgSequence = class {
      constructor(seqName, seqOptions, schema5) {
        this.seqName = seqName;
        this.seqOptions = seqOptions;
        this.schema = schema5;
      }
    };
    __publicField(PgSequence, _a163, "PgSequence");
  }
});

// ../drizzle-orm/dist/pg-core/schema.js
var _a164, PgSchema5;
var init_schema = __esm({
  "../drizzle-orm/dist/pg-core/schema.js"() {
    "use strict";
    init_entity();
    init_sql();
    init_enum();
    init_sequence();
    init_table2();
    init_view();
    _a164 = entityKind;
    PgSchema5 = class {
      constructor(schemaName) {
        __publicField(this, "table", (name2, columns, extraConfig) => {
          return pgTableWithSchema(name2, columns, extraConfig, this.schemaName);
        });
        __publicField(this, "view", (name2, columns) => {
          return pgViewWithSchema(name2, columns, this.schemaName);
        });
        __publicField(this, "materializedView", (name2, columns) => {
          return pgMaterializedViewWithSchema(name2, columns, this.schemaName);
        });
        __publicField(this, "sequence", (name2, options) => {
          return pgSequenceWithSchema(name2, options, this.schemaName);
        });
        this.schemaName = schemaName;
      }
      enum(enumName, input) {
        return Array.isArray(input) ? pgEnumWithSchema(
          enumName,
          [...input],
          this.schemaName
        ) : pgEnumObjectWithSchema(enumName, input, this.schemaName);
      }
      getSQL() {
        return new SQL([sql.identifier(this.schemaName)]);
      }
      shouldOmitSQLParens() {
        return true;
      }
    };
    __publicField(PgSchema5, _a164, "PgSchema");
  }
});

// ../drizzle-orm/dist/cache/core/cache.js
async function hashQuery(sql2, params) {
  const dataToHash = `${sql2}-${JSON.stringify(params)}`;
  const encoder = new TextEncoder();
  const data = encoder.encode(dataToHash);
  const hashBuffer = await crypto.subtle.digest("SHA-256", data);
  const hashArray = [...new Uint8Array(hashBuffer)];
  const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
  return hashHex;
}
var _a165, Cache, _a166, _b119, NoopCache;
var init_cache = __esm({
  "../drizzle-orm/dist/cache/core/cache.js"() {
    "use strict";
    init_entity();
    _a165 = entityKind;
    Cache = class {
    };
    __publicField(Cache, _a165, "Cache");
    NoopCache = class extends (_b119 = Cache, _a166 = entityKind, _b119) {
      strategy() {
        return "all";
      }
      async get(_key) {
        return void 0;
      }
      async put(_hashedQuery, _response, _tables, _config) {
      }
      async onMutate(_params) {
      }
    };
    __publicField(NoopCache, _a166, "NoopCache");
  }
});

// ../drizzle-orm/dist/errors/index.js
var DrizzleQueryError;
var init_errors3 = __esm({
  "../drizzle-orm/dist/errors/index.js"() {
    "use strict";
    DrizzleQueryError = class _DrizzleQueryError extends Error {
      constructor(query, params, cause) {
        super(`Failed query: ${query}
params: ${params}`);
        this.query = query;
        this.params = params;
        this.cause = cause;
        Error.captureStackTrace(this, _DrizzleQueryError);
        if (cause) this.cause = cause;
      }
    };
  }
});

// ../drizzle-orm/dist/pg-core/session.js
var _a167, PgPreparedQuery, _a168, PgSession, _a169, _b120, PgTransaction;
var init_session = __esm({
  "../drizzle-orm/dist/pg-core/session.js"() {
    "use strict";
    init_cache();
    init_entity();
    init_errors2();
    init_errors3();
    init_sql2();
    init_tracing();
    init_db();
    _a167 = entityKind;
    PgPreparedQuery = class {
      constructor(query, cache, queryMetadata, cacheConfig) {
        __publicField(this, "authToken");
        /** @internal */
        __publicField(this, "joinsNotNullableMap");
        this.query = query;
        this.cache = cache;
        this.queryMetadata = queryMetadata;
        this.cacheConfig = cacheConfig;
        if (cache && cache.strategy() === "all" && cacheConfig === void 0) {
          this.cacheConfig = { enable: true, autoInvalidate: true };
        }
        if (!this.cacheConfig?.enable) {
          this.cacheConfig = void 0;
        }
      }
      getQuery() {
        return this.query;
      }
      mapResult(response, _isFromBatch) {
        return response;
      }
      /** @internal */
      setToken(token) {
        this.authToken = token;
        return this;
      }
      /** @internal */
      async queryWithCache(queryString, params, query) {
        if (this.cache === void 0 || is(this.cache, NoopCache) || this.queryMetadata === void 0) {
          try {
            return await query();
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if (this.cacheConfig && !this.cacheConfig.enable) {
          try {
            return await query();
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) {
          try {
            const [res] = await Promise.all([
              query(),
              this.cache.onMutate({ tables: this.queryMetadata.tables })
            ]);
            return res;
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if (!this.cacheConfig) {
          try {
            return await query();
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if (this.queryMetadata.type === "select") {
          const fromCache = await this.cache.get(
            this.cacheConfig.tag ?? await hashQuery(queryString, params),
            this.queryMetadata.tables,
            this.cacheConfig.tag !== void 0,
            this.cacheConfig.autoInvalidate
          );
          if (fromCache === void 0) {
            let result;
            try {
              result = await query();
            } catch (e) {
              throw new DrizzleQueryError(queryString, params, e);
            }
            await this.cache.put(
              this.cacheConfig.tag ?? await hashQuery(queryString, params),
              result,
              // make sure we send tables that were used in a query only if user wants to invalidate it on each write
              this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [],
              this.cacheConfig.tag !== void 0,
              this.cacheConfig.config
            );
            return result;
          }
          return fromCache;
        }
        try {
          return await query();
        } catch (e) {
          throw new DrizzleQueryError(queryString, params, e);
        }
      }
    };
    __publicField(PgPreparedQuery, _a167, "PgPreparedQuery");
    _a168 = entityKind;
    PgSession = class {
      constructor(dialect6) {
        this.dialect = dialect6;
      }
      /** @internal */
      execute(query, token) {
        return tracer.startActiveSpan("drizzle.operation", () => {
          const prepared = tracer.startActiveSpan("drizzle.prepareQuery", () => {
            return this.prepareQuery(
              this.dialect.sqlToQuery(query),
              void 0,
              void 0,
              false
            );
          });
          return prepared.setToken(token).execute(void 0, token);
        });
      }
      all(query) {
        return this.prepareQuery(
          this.dialect.sqlToQuery(query),
          void 0,
          void 0,
          false
        ).all();
      }
      /** @internal */
      async count(sql2, token) {
        const res = await this.execute(sql2, token);
        return Number(
          res[0]["count"]
        );
      }
    };
    __publicField(PgSession, _a168, "PgSession");
    PgTransaction = class extends (_b120 = PgDatabase, _a169 = entityKind, _b120) {
      constructor(dialect6, session, schema5, nestedIndex = 0) {
        super(dialect6, session, schema5);
        this.schema = schema5;
        this.nestedIndex = nestedIndex;
      }
      rollback() {
        throw new TransactionRollbackError();
      }
      /** @internal */
      getTransactionConfigSQL(config) {
        const chunks = [];
        if (config.isolationLevel) {
          chunks.push(`isolation level ${config.isolationLevel}`);
        }
        if (config.accessMode) {
          chunks.push(config.accessMode);
        }
        if (typeof config.deferrable === "boolean") {
          chunks.push(config.deferrable ? "deferrable" : "not deferrable");
        }
        return sql.raw(chunks.join(" "));
      }
      setTransaction(config) {
        return this.session.execute(sql`set transaction ${this.getTransactionConfigSQL(config)}`);
      }
    };
    __publicField(PgTransaction, _a169, "PgTransaction");
  }
});

// ../drizzle-orm/dist/pg-core/subquery.js
var init_subquery2 = __esm({
  "../drizzle-orm/dist/pg-core/subquery.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/pg-core/utils/index.js
var init_utils5 = __esm({
  "../drizzle-orm/dist/pg-core/utils/index.js"() {
    "use strict";
    init_array();
  }
});

// ../drizzle-orm/dist/pg-core/index.js
var init_pg_core = __esm({
  "../drizzle-orm/dist/pg-core/index.js"() {
    "use strict";
    init_alias2();
    init_checks();
    init_columns();
    init_db();
    init_dialect();
    init_foreign_keys();
    init_indexes();
    init_policies();
    init_primary_keys();
    init_query_builders();
    init_roles();
    init_schema();
    init_sequence();
    init_session();
    init_subquery2();
    init_table2();
    init_unique_constraint();
    init_utils4();
    init_utils5();
    init_view_common2();
    init_view();
  }
});

// src/extensions/vector.ts
var vectorOps;
var init_vector3 = __esm({
  "src/extensions/vector.ts"() {
    "use strict";
    vectorOps = [
      "vector_l2_ops",
      "vector_ip_ops",
      "vector_cosine_ops",
      "vector_l1_ops",
      "bit_hamming_ops",
      "bit_jaccard_ops",
      "halfvec_l2_ops",
      "sparsevec_l2_ops"
    ];
  }
});

// src/serializer/utils.ts
function getColumnCasing(column6, casing2) {
  if (!column6.name) return "";
  return !column6.keyAsName || casing2 === void 0 ? column6.name : casing2 === "camelCase" ? toCamelCase(column6.name) : toSnakeCase(column6.name);
}
var sqlToStr;
var init_utils6 = __esm({
  "src/serializer/utils.ts"() {
    "use strict";
    init_casing();
    sqlToStr = (sql2, casing2) => {
      return sql2.toQuery({
        escapeName: () => {
          throw new Error("we don't support params for `sql` default values");
        },
        escapeParam: () => {
          throw new Error("we don't support params for `sql` default values");
        },
        escapeString: () => {
          throw new Error("we don't support params for `sql` default values");
        },
        casing: new CasingCache(casing2)
      }).sql;
    };
  }
});

// src/serializer/pgSerializer.ts
function stringFromIdentityProperty(field) {
  return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : String(field);
}
function maxRangeForIdentityBasedOn(columnType) {
  return columnType === "integer" ? "2147483647" : columnType === "bigint" ? "9223372036854775807" : "32767";
}
function minRangeForIdentityBasedOn(columnType) {
  return columnType === "integer" ? "-2147483648" : columnType === "bigint" ? "-9223372036854775808" : "-32768";
}
function stringFromDatabaseIdentityProperty(field) {
  return typeof field === "string" ? field : typeof field === "undefined" ? void 0 : typeof field === "bigint" ? field.toString() : String(field);
}
function buildArrayString(array2, sqlType) {
  sqlType = sqlType.split("[")[0];
  const values = array2.map((value) => {
    if (typeof value === "number" || typeof value === "bigint") {
      return value.toString();
    } else if (typeof value === "boolean") {
      return value ? "true" : "false";
    } else if (Array.isArray(value)) {
      return buildArrayString(value, sqlType);
    } else if (value instanceof Date) {
      if (sqlType === "date") {
        return `"${value.toISOString().split("T")[0]}"`;
      } else if (sqlType === "timestamp") {
        return `"${value.toISOString().replace("T", " ").slice(0, 23)}"`;
      } else {
        return `"${value.toISOString()}"`;
      }
    } else if (typeof value === "object") {
      return `"${JSON.stringify(value).replaceAll('"', '\\"')}"`;
    }
    return `"${value}"`;
  }).join(",");
  return `{${values}}`;
}
function prepareRoles(entities) {
  let useRoles = false;
  const includeRoles = [];
  const excludeRoles = [];
  if (entities && entities.roles) {
    if (typeof entities.roles === "object") {
      if (entities.roles.provider) {
        if (entities.roles.provider === "supabase") {
          excludeRoles.push(...[
            "anon",
            "authenticator",
            "authenticated",
            "service_role",
            "supabase_auth_admin",
            "supabase_storage_admin",
            "dashboard_user",
            "supabase_admin"
          ]);
        } else if (entities.roles.provider === "neon") {
          excludeRoles.push(...["authenticated", "anonymous"]);
        }
      }
      if (entities.roles.include) {
        includeRoles.push(...entities.roles.include);
      }
      if (entities.roles.exclude) {
        excludeRoles.push(...entities.roles.exclude);
      }
    } else {
      useRoles = entities.roles;
    }
  }
  return { useRoles, includeRoles, excludeRoles };
}
var indexName, generatePgSnapshot, trimChar, fromDatabase, defaultForColumn, getColumnsInfoQuery;
var init_pgSerializer = __esm({
  "src/serializer/pgSerializer.ts"() {
    "use strict";
    init_source();
    init_dist();
    init_pg_core();
    init_vector3();
    init_outputs();
    init_utils();
    init_utils6();
    indexName = (tableName, columns) => {
      return `${tableName}_${columns.join("_")}_index`;
    };
    generatePgSnapshot = (tables, enums, schemas, sequences, roles, policies, views, matViews, casing2, schemaFilter) => {
      const dialect6 = new PgDialect({ casing: casing2 });
      const result = {};
      const resultViews = {};
      const sequencesToReturn = {};
      const rolesToReturn = {};
      const policiesToReturn = {};
      const indexesInSchema = {};
      for (const table6 of tables) {
        const checksInTable = {};
        const {
          name: tableName,
          columns,
          indexes,
          foreignKeys,
          checks,
          schema: schema5,
          primaryKeys,
          uniqueConstraints,
          policies: policies2,
          enableRLS
        } = getTableConfig(table6);
        if (schemaFilter && !schemaFilter.includes(schema5 ?? "public")) {
          continue;
        }
        const columnsObject = {};
        const indexesObject = {};
        const checksObject = {};
        const foreignKeysObject = {};
        const primaryKeysObject = {};
        const uniqueConstraintObject = {};
        const policiesObject = {};
        columns.forEach((column6) => {
          const name2 = getColumnCasing(column6, casing2);
          const notNull = column6.notNull;
          const primaryKey = column6.primary;
          const sqlTypeLowered = column6.getSQLType().toLowerCase();
          const getEnumSchema = (column7) => {
            while (is(column7, PgArray)) {
              column7 = column7.baseColumn;
            }
            return is(column7, PgEnumColumn) ? column7.enum.schema || "public" : void 0;
          };
          const typeSchema = getEnumSchema(column6);
          const generated = column6.generated;
          const identity = column6.generatedIdentity;
          const increment = stringFromIdentityProperty(identity?.sequenceOptions?.increment) ?? "1";
          const minValue = stringFromIdentityProperty(identity?.sequenceOptions?.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column6.columnType) : "1");
          const maxValue = stringFromIdentityProperty(identity?.sequenceOptions?.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column6.getSQLType()));
          const startWith = stringFromIdentityProperty(identity?.sequenceOptions?.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
          const cache = stringFromIdentityProperty(identity?.sequenceOptions?.cache) ?? "1";
          const columnToSet = {
            name: name2,
            type: column6.getSQLType(),
            typeSchema,
            primaryKey,
            notNull,
            generated: generated ? {
              as: is(generated.as, SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
              type: "stored"
            } : void 0,
            identity: identity ? {
              type: identity.type,
              name: identity.sequenceName ?? `${tableName}_${name2}_seq`,
              schema: schema5 ?? "public",
              increment,
              startWith,
              minValue,
              maxValue,
              cache,
              cycle: identity?.sequenceOptions?.cycle ?? false
            } : void 0
          };
          if (column6.isUnique) {
            const existingUnique = uniqueConstraintObject[column6.uniqueName];
            if (typeof existingUnique !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
          The unique constraint ${source_default.underline.blue(
                  column6.uniqueName
                )} on the ${source_default.underline.blue(
                  name2
                )} column is conflicting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`)}`
              );
              process.exit(1);
            }
            uniqueConstraintObject[column6.uniqueName] = {
              name: column6.uniqueName,
              nullsNotDistinct: column6.uniqueType === "not distinct",
              columns: [columnToSet.name]
            };
          }
          if (column6.default !== void 0) {
            if (is(column6.default, SQL)) {
              columnToSet.default = sqlToStr(column6.default, casing2);
            } else {
              if (typeof column6.default === "string") {
                columnToSet.default = `'${escapeSingleQuotes(column6.default)}'`;
              } else {
                if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
                  columnToSet.default = `'${JSON.stringify(column6.default)}'::${sqlTypeLowered}`;
                } else if (column6.default instanceof Date) {
                  if (sqlTypeLowered === "date") {
                    columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`;
                  } else if (sqlTypeLowered === "timestamp") {
                    columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                  } else {
                    columnToSet.default = `'${column6.default.toISOString()}'`;
                  }
                } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column6.default)) {
                  columnToSet.default = `'${buildArrayString(column6.default, sqlTypeLowered)}'`;
                } else {
                  columnToSet.default = column6.default;
                }
              }
            }
          }
          columnsObject[name2] = columnToSet;
        });
        primaryKeys.map((pk) => {
          const originalColumnNames = pk.columns.map((c) => c.name);
          const columnNames = pk.columns.map((c) => getColumnCasing(c, casing2));
          let name2 = pk.getName();
          if (casing2 !== void 0) {
            for (let i = 0; i < originalColumnNames.length; i++) {
              name2 = name2.replace(originalColumnNames[i], columnNames[i]);
            }
          }
          primaryKeysObject[name2] = {
            name: name2,
            columns: columnNames
          };
        });
        uniqueConstraints?.map((unq) => {
          const columnNames = unq.columns.map((c) => getColumnCasing(c, casing2));
          const name2 = unq.name ?? uniqueKeyName(table6, columnNames);
          const existingUnique = uniqueConstraintObject[name2];
          if (typeof existingUnique !== "undefined") {
            console.log(
              `
${withStyle.errorWarning(
                `We've found duplicated unique constraint names in ${source_default.underline.blue(tableName)} table. 
        The unique constraint ${source_default.underline.blue(name2)} on the ${source_default.underline.blue(
                  columnNames.join(",")
                )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
`
              )}`
            );
            process.exit(1);
          }
          uniqueConstraintObject[name2] = {
            name: unq.name,
            nullsNotDistinct: unq.nullsNotDistinct,
            columns: columnNames
          };
        });
        const fks = foreignKeys.map((fk5) => {
          const tableFrom = tableName;
          const onDelete = fk5.onDelete;
          const onUpdate = fk5.onUpdate;
          const reference = fk5.reference();
          const tableTo = getTableName(reference.foreignTable);
          const schemaTo = getTableConfig(reference.foreignTable).schema;
          const originalColumnsFrom = reference.columns.map((it) => it.name);
          const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2));
          const originalColumnsTo = reference.foreignColumns.map((it) => it.name);
          const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2));
          let name2 = fk5.getName();
          if (casing2 !== void 0) {
            for (let i = 0; i < originalColumnsFrom.length; i++) {
              name2 = name2.replace(originalColumnsFrom[i], columnsFrom[i]);
            }
            for (let i = 0; i < originalColumnsTo.length; i++) {
              name2 = name2.replace(originalColumnsTo[i], columnsTo[i]);
            }
          }
          return {
            name: name2,
            tableFrom,
            tableTo,
            schemaTo,
            columnsFrom,
            columnsTo,
            onDelete,
            onUpdate
          };
        });
        fks.forEach((it) => {
          foreignKeysObject[it.name] = it;
        });
        indexes.forEach((value) => {
          const columns2 = value.config.columns;
          let indexColumnNames = [];
          columns2.forEach((it) => {
            if (is(it, SQL)) {
              if (typeof value.config.name === "undefined") {
                console.log(
                  `
${withStyle.errorWarning(
                    `Please specify an index name in ${getTableName(value.config.table)} table that has "${dialect6.sqlToQuery(it).sql}" expression. We can generate index names for indexes on columns only; for expressions in indexes, you need to specify the name yourself.`
                  )}`
                );
                process.exit(1);
              }
            }
            it = it;
            const name3 = getColumnCasing(it, casing2);
            if (!is(it, SQL) && it.type === "PgVector" && typeof it.indexConfig.opClass === "undefined") {
              console.log(
                `
${withStyle.errorWarning(
                  `You are specifying an index on the ${source_default.blueBright(
                    name3
                  )} column inside the ${source_default.blueBright(
                    tableName
                  )} table with the ${source_default.blueBright(
                    "vector"
                  )} type without specifying an operator class. Vector extension doesn't have a default operator class, so you need to specify one of the available options. Here is a list of available op classes for the vector extension: [${vectorOps.map((it2) => `${source_default.underline(`${it2}`)}`).join(", ")}].

You can specify it using current syntax: ${source_default.underline(
                    `index("${value.config.name}").using("${value.config.method}", table.${name3}.op("${vectorOps[0]}"))`
                  )}

You can check the "pg_vector" docs for more info: https://github.com/pgvector/pgvector?tab=readme-ov-file#indexing
`
                )}`
              );
              process.exit(1);
            }
            indexColumnNames.push(name3);
          });
          const name2 = value.config.name ? value.config.name : indexName(tableName, indexColumnNames);
          let indexColumns = columns2.map(
            (it) => {
              if (is(it, SQL)) {
                return {
                  expression: dialect6.sqlToQuery(it, "indexes").sql,
                  asc: true,
                  isExpression: true,
                  nulls: "last"
                };
              } else {
                it = it;
                return {
                  expression: getColumnCasing(it, casing2),
                  isExpression: false,
                  asc: it.indexConfig?.order === "asc",
                  nulls: it.indexConfig?.nulls ? it.indexConfig?.nulls : it.indexConfig?.order === "desc" ? "first" : "last",
                  opclass: it.indexConfig?.opClass
                };
              }
            }
          );
          if (typeof indexesInSchema[schema5 ?? "public"] !== "undefined") {
            if (indexesInSchema[schema5 ?? "public"].includes(name2)) {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated index name across ${source_default.underline.blue(schema5 ?? "public")} schema. Please rename your index in either the ${source_default.underline.blue(
                    tableName
                  )} table or the table with the duplicated index name`
                )}`
              );
              process.exit(1);
            }
            indexesInSchema[schema5 ?? "public"].push(name2);
          } else {
            indexesInSchema[schema5 ?? "public"] = [name2];
          }
          indexesObject[name2] = {
            name: name2,
            columns: indexColumns,
            isUnique: value.config.unique ?? false,
            where: value.config.where ? dialect6.sqlToQuery(value.config.where).sql : void 0,
            concurrently: value.config.concurrently ?? false,
            method: value.config.method ?? "btree",
            with: value.config.with ?? {}
          };
        });
        policies2.forEach((policy5) => {
          const mappedTo = [];
          if (!policy5.to) {
            mappedTo.push("public");
          } else {
            if (policy5.to && typeof policy5.to === "string") {
              mappedTo.push(policy5.to);
            } else if (policy5.to && is(policy5.to, PgRole)) {
              mappedTo.push(policy5.to.name);
            } else if (policy5.to && Array.isArray(policy5.to)) {
              policy5.to.forEach((it) => {
                if (typeof it === "string") {
                  mappedTo.push(it);
                } else if (is(it, PgRole)) {
                  mappedTo.push(it.name);
                }
              });
            }
          }
          if (policiesObject[policy5.name] !== void 0) {
            console.log(
              `
${withStyle.errorWarning(
                `We've found duplicated policy name across ${source_default.underline.blue(tableKey2)} table. Please rename one of the policies with ${source_default.underline.blue(
                  policy5.name
                )} name`
              )}`
            );
            process.exit(1);
          }
          policiesObject[policy5.name] = {
            name: policy5.name,
            as: policy5.as?.toUpperCase() ?? "PERMISSIVE",
            for: policy5.for?.toUpperCase() ?? "ALL",
            to: mappedTo.sort(),
            using: is(policy5.using, SQL) ? dialect6.sqlToQuery(policy5.using).sql : void 0,
            withCheck: is(policy5.withCheck, SQL) ? dialect6.sqlToQuery(policy5.withCheck).sql : void 0
          };
        });
        checks.forEach((check) => {
          const checkName = check.name;
          if (typeof checksInTable[`"${schema5 ?? "public"}"."${tableName}"`] !== "undefined") {
            if (checksInTable[`"${schema5 ?? "public"}"."${tableName}"`].includes(check.name)) {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated check constraint name across ${source_default.underline.blue(
                    schema5 ?? "public"
                  )} schema in ${source_default.underline.blue(
                    tableName
                  )}. Please rename your check constraint in either the ${source_default.underline.blue(
                    tableName
                  )} table or the table with the duplicated check contraint name`
                )}`
              );
              process.exit(1);
            }
            checksInTable[`"${schema5 ?? "public"}"."${tableName}"`].push(checkName);
          } else {
            checksInTable[`"${schema5 ?? "public"}"."${tableName}"`] = [check.name];
          }
          checksObject[checkName] = {
            name: checkName,
            value: dialect6.sqlToQuery(check.value).sql
          };
        });
        const tableKey2 = `${schema5 ?? "public"}.${tableName}`;
        result[tableKey2] = {
          name: tableName,
          schema: schema5 ?? "",
          columns: columnsObject,
          indexes: indexesObject,
          foreignKeys: foreignKeysObject,
          compositePrimaryKeys: primaryKeysObject,
          uniqueConstraints: uniqueConstraintObject,
          policies: policiesObject,
          checkConstraints: checksObject,
          isRLSEnabled: enableRLS
        };
      }
      for (const policy5 of policies) {
        if (!policy5._linkedTable) {
          console.log(
            `
${withStyle.errorWarning(
              `"Policy ${policy5.name} was skipped because it was not linked to any table. You should either include the policy in a table or use .link() on the policy to link it to any table you have. For more information, please check:`
            )}`
          );
          continue;
        }
        const tableConfig = getTableConfig(policy5._linkedTable);
        const tableKey2 = `${tableConfig.schema ?? "public"}.${tableConfig.name}`;
        const mappedTo = [];
        if (!policy5.to) {
          mappedTo.push("public");
        } else {
          if (policy5.to && typeof policy5.to === "string") {
            mappedTo.push(policy5.to);
          } else if (policy5.to && is(policy5.to, PgRole)) {
            mappedTo.push(policy5.to.name);
          } else if (policy5.to && Array.isArray(policy5.to)) {
            policy5.to.forEach((it) => {
              if (typeof it === "string") {
                mappedTo.push(it);
              } else if (is(it, PgRole)) {
                mappedTo.push(it.name);
              }
            });
          }
        }
        if (result[tableKey2]?.policies[policy5.name] !== void 0 || policiesToReturn[policy5.name] !== void 0) {
          console.log(
            `
${withStyle.errorWarning(
              `We've found duplicated policy name across ${source_default.underline.blue(tableKey2)} table. Please rename one of the policies with ${source_default.underline.blue(
                policy5.name
              )} name`
            )}`
          );
          process.exit(1);
        }
        const mappedPolicy = {
          name: policy5.name,
          as: policy5.as?.toUpperCase() ?? "PERMISSIVE",
          for: policy5.for?.toUpperCase() ?? "ALL",
          to: mappedTo.sort(),
          using: is(policy5.using, SQL) ? dialect6.sqlToQuery(policy5.using).sql : void 0,
          withCheck: is(policy5.withCheck, SQL) ? dialect6.sqlToQuery(policy5.withCheck).sql : void 0
        };
        if (result[tableKey2]) {
          result[tableKey2].policies[policy5.name] = mappedPolicy;
        } else {
          policiesToReturn[policy5.name] = {
            ...mappedPolicy,
            schema: tableConfig.schema ?? "public",
            on: `"${tableConfig.schema ?? "public"}"."${tableConfig.name}"`
          };
        }
      }
      for (const sequence of sequences) {
        const name2 = sequence.seqName;
        if (typeof sequencesToReturn[`${sequence.schema ?? "public"}.${name2}`] === "undefined") {
          const increment = stringFromIdentityProperty(sequence?.seqOptions?.increment) ?? "1";
          const minValue = stringFromIdentityProperty(sequence?.seqOptions?.minValue) ?? (parseFloat(increment) < 0 ? "-9223372036854775808" : "1");
          const maxValue = stringFromIdentityProperty(sequence?.seqOptions?.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : "9223372036854775807");
          const startWith = stringFromIdentityProperty(sequence?.seqOptions?.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
          const cache = stringFromIdentityProperty(sequence?.seqOptions?.cache) ?? "1";
          sequencesToReturn[`${sequence.schema ?? "public"}.${name2}`] = {
            name: name2,
            schema: sequence.schema ?? "public",
            increment,
            startWith,
            minValue,
            maxValue,
            cache,
            cycle: sequence.seqOptions?.cycle ?? false
          };
        } else {
        }
      }
      for (const role of roles) {
        if (!role._existing) {
          rolesToReturn[role.name] = {
            name: role.name,
            createDb: role.createDb === void 0 ? false : role.createDb,
            createRole: role.createRole === void 0 ? false : role.createRole,
            inherit: role.inherit === void 0 ? true : role.inherit
          };
        }
      }
      const combinedViews = [...views, ...matViews];
      for (const view5 of combinedViews) {
        let viewName;
        let schema5;
        let query;
        let selectedFields;
        let isExisting;
        let withOption;
        let tablespace;
        let using;
        let withNoData;
        let materialized = false;
        if (is(view5, PgView2)) {
          ({ name: viewName, schema: schema5, query, selectedFields, isExisting, with: withOption } = getViewConfig(view5));
        } else {
          ({ name: viewName, schema: schema5, query, selectedFields, isExisting, with: withOption, tablespace, using, withNoData } = getMaterializedViewConfig(view5));
          materialized = true;
        }
        const viewSchema = schema5 ?? "public";
        const viewKey = `${viewSchema}.${viewName}`;
        const columnsObject = {};
        const uniqueConstraintObject = {};
        const existingView = resultViews[viewKey];
        if (typeof existingView !== "undefined") {
          console.log(
            `
${withStyle.errorWarning(
              `We've found duplicated view name across ${source_default.underline.blue(schema5 ?? "public")} schema. Please rename your view`
            )}`
          );
          process.exit(1);
        }
        for (const key in selectedFields) {
          if (is(selectedFields[key], PgColumn)) {
            const column6 = selectedFields[key];
            const notNull = column6.notNull;
            const primaryKey = column6.primary;
            const sqlTypeLowered = column6.getSQLType().toLowerCase();
            const typeSchema = is(column6, PgEnumColumn) ? column6.enum.schema || "public" : void 0;
            const generated = column6.generated;
            const identity = column6.generatedIdentity;
            const increment = stringFromIdentityProperty(identity?.sequenceOptions?.increment) ?? "1";
            const minValue = stringFromIdentityProperty(identity?.sequenceOptions?.minValue) ?? (parseFloat(increment) < 0 ? minRangeForIdentityBasedOn(column6.columnType) : "1");
            const maxValue = stringFromIdentityProperty(identity?.sequenceOptions?.maxValue) ?? (parseFloat(increment) < 0 ? "-1" : maxRangeForIdentityBasedOn(column6.getSQLType()));
            const startWith = stringFromIdentityProperty(identity?.sequenceOptions?.startWith) ?? (parseFloat(increment) < 0 ? maxValue : minValue);
            const cache = stringFromIdentityProperty(identity?.sequenceOptions?.cache) ?? "1";
            const columnToSet = {
              name: column6.name,
              type: column6.getSQLType(),
              typeSchema,
              primaryKey,
              notNull,
              generated: generated ? {
                as: is(generated.as, SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
                type: "stored"
              } : void 0,
              identity: identity ? {
                type: identity.type,
                name: identity.sequenceName ?? `${viewName}_${column6.name}_seq`,
                schema: schema5 ?? "public",
                increment,
                startWith,
                minValue,
                maxValue,
                cache,
                cycle: identity?.sequenceOptions?.cycle ?? false
              } : void 0
            };
            if (column6.isUnique) {
              const existingUnique = uniqueConstraintObject[column6.uniqueName];
              if (typeof existingUnique !== "undefined") {
                console.log(
                  `
${withStyle.errorWarning(
                    `We've found duplicated unique constraint names in ${source_default.underline.blue(viewName)} table. 
          The unique constraint ${source_default.underline.blue(column6.uniqueName)} on the ${source_default.underline.blue(
                      column6.name
                    )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(existingUnique.columns.join(","))} columns
`
                  )}`
                );
                process.exit(1);
              }
              uniqueConstraintObject[column6.uniqueName] = {
                name: column6.uniqueName,
                nullsNotDistinct: column6.uniqueType === "not distinct",
                columns: [columnToSet.name]
              };
            }
            if (column6.default !== void 0) {
              if (is(column6.default, SQL)) {
                columnToSet.default = sqlToStr(column6.default, casing2);
              } else {
                if (typeof column6.default === "string") {
                  columnToSet.default = `'${column6.default}'`;
                } else {
                  if (sqlTypeLowered === "jsonb" || sqlTypeLowered === "json") {
                    columnToSet.default = `'${JSON.stringify(column6.default)}'::${sqlTypeLowered}`;
                  } else if (column6.default instanceof Date) {
                    if (sqlTypeLowered === "date") {
                      columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`;
                    } else if (sqlTypeLowered === "timestamp") {
                      columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                    } else {
                      columnToSet.default = `'${column6.default.toISOString()}'`;
                    }
                  } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column6.default)) {
                    columnToSet.default = `'${buildArrayString(column6.default, sqlTypeLowered)}'`;
                  } else {
                    columnToSet.default = column6.default;
                  }
                }
              }
            }
            columnsObject[column6.name] = columnToSet;
          }
        }
        resultViews[viewKey] = {
          columns: columnsObject,
          definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql,
          name: viewName,
          schema: viewSchema,
          isExisting,
          with: withOption,
          withNoData,
          materialized,
          tablespace,
          using
        };
      }
      const enumsToReturn = enums.reduce((map, obj) => {
        const enumSchema4 = obj.schema || "public";
        const key = `${enumSchema4}.${obj.enumName}`;
        map[key] = {
          name: obj.enumName,
          schema: enumSchema4,
          values: obj.enumValues
        };
        return map;
      }, {});
      const schemasObject = Object.fromEntries(
        schemas.filter((it) => {
          if (schemaFilter) {
            return schemaFilter.includes(it.schemaName) && it.schemaName !== "public";
          } else {
            return it.schemaName !== "public";
          }
        }).map((it) => [it.schemaName, it.schemaName])
      );
      return {
        version: "7",
        dialect: "postgresql",
        tables: result,
        enums: enumsToReturn,
        schemas: schemasObject,
        sequences: sequencesToReturn,
        roles: rolesToReturn,
        policies: policiesToReturn,
        views: resultViews,
        _meta: {
          schemas: {},
          tables: {},
          columns: {}
        }
      };
    };
    trimChar = (str, char4) => {
      let start = 0;
      let end = str.length;
      while (start < end && str[start] === char4) ++start;
      while (end > start && str[end - 1] === char4) --end;
      return start > 0 || end < str.length ? str.substring(start, end) : str.toString();
    };
    fromDatabase = async (db, tablesFilter = () => true, schemaFilters, entities, progressCallback, tsSchema) => {
      const result = {};
      const views = {};
      const policies = {};
      const internals = { tables: {} };
      const where = schemaFilters.map((t) => `n.nspname = '${t}'`).join(" or ");
      const allTables = await db.query(
        `SELECT 
    n.nspname AS table_schema, 
    c.relname AS table_name, 
    CASE 
        WHEN c.relkind = 'r' THEN 'table'
        WHEN c.relkind = 'v' THEN 'view'
        WHEN c.relkind = 'm' THEN 'materialized_view'
    END AS type,
	c.relrowsecurity AS rls_enabled
FROM 
    pg_catalog.pg_class c
JOIN 
    pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE 
	c.relkind IN ('r', 'v', 'm') 
    ${where === "" ? "" : ` AND ${where}`};`
      );
      const schemas = new Set(allTables.map((it) => it.table_schema));
      schemas.delete("public");
      const allSchemas = await db.query(`select s.nspname as table_schema
  from pg_catalog.pg_namespace s
  join pg_catalog.pg_user u on u.usesysid = s.nspowner
  where nspname not in ('information_schema', 'pg_catalog', 'public')
        and nspname not like 'pg_toast%'
        and nspname not like 'pg_temp_%'
  order by table_schema;`);
      allSchemas.forEach((item) => {
        if (schemaFilters.includes(item.table_schema)) {
          schemas.add(item.table_schema);
        }
      });
      let columnsCount = 0;
      let indexesCount = 0;
      let foreignKeysCount = 0;
      let tableCount = 0;
      let checksCount = 0;
      let viewsCount = 0;
      const sequencesToReturn = {};
      const seqWhere = schemaFilters.map((t) => `schemaname = '${t}'`).join(" or ");
      const allSequences = await db.query(
        `select schemaname, sequencename, start_value, min_value, max_value, increment_by, cycle, cache_size from pg_sequences as seq${seqWhere === "" ? "" : ` WHERE ${seqWhere}`};`
      );
      for (const dbSeq of allSequences) {
        const schemaName = dbSeq.schemaname;
        const sequenceName = dbSeq.sequencename;
        const startValue = stringFromDatabaseIdentityProperty(dbSeq.start_value);
        const minValue = stringFromDatabaseIdentityProperty(dbSeq.min_value);
        const maxValue = stringFromDatabaseIdentityProperty(dbSeq.max_value);
        const incrementBy = stringFromDatabaseIdentityProperty(dbSeq.increment_by);
        const cycle = dbSeq.cycle;
        const cacheSize = stringFromDatabaseIdentityProperty(dbSeq.cache_size);
        const key = `${schemaName}.${sequenceName}`;
        sequencesToReturn[key] = {
          name: sequenceName,
          schema: schemaName,
          startWith: startValue,
          minValue,
          maxValue,
          increment: incrementBy,
          cycle,
          cache: cacheSize
        };
      }
      const whereEnums = schemaFilters.map((t) => `n.nspname = '${t}'`).join(" or ");
      const allEnums = await db.query(
        `select n.nspname as enum_schema,
  t.typname as enum_name,
  e.enumlabel as enum_value,
  e.enumsortorder as sort_order
  from pg_type t
  join pg_enum e on t.oid = e.enumtypid
  join pg_catalog.pg_namespace n ON n.oid = t.typnamespace
  ${whereEnums === "" ? "" : ` WHERE ${whereEnums}`}
  order by enum_schema, enum_name, sort_order;`
      );
      const enumsToReturn = {};
      for (const dbEnum of allEnums) {
        const enumName = dbEnum.enum_name;
        const enumValue = dbEnum.enum_value;
        const enumSchema4 = dbEnum.enum_schema || "public";
        const key = `${enumSchema4}.${enumName}`;
        if (enumsToReturn[key] !== void 0 && enumsToReturn[key] !== null) {
          enumsToReturn[key].values.push(enumValue);
        } else {
          enumsToReturn[key] = {
            name: enumName,
            values: [enumValue],
            schema: enumSchema4
          };
        }
      }
      if (progressCallback) {
        progressCallback("enums", Object.keys(enumsToReturn).length, "done");
      }
      const allRoles = await db.query(
        `SELECT rolname, rolinherit, rolcreatedb, rolcreaterole FROM pg_roles;`
      );
      const rolesToReturn = {};
      const preparedRoles = prepareRoles(entities);
      if (preparedRoles.useRoles || !(preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0)) {
        for (const dbRole of allRoles) {
          if (preparedRoles.useRoles) {
            rolesToReturn[dbRole.rolname] = {
              createDb: dbRole.rolcreatedb,
              createRole: dbRole.rolcreatedb,
              inherit: dbRole.rolinherit,
              name: dbRole.rolname
            };
          } else {
            if (preparedRoles.includeRoles.length === 0 && preparedRoles.excludeRoles.length === 0) continue;
            if (preparedRoles.includeRoles.includes(dbRole.rolname) && preparedRoles.excludeRoles.includes(dbRole.rolname)) continue;
            if (preparedRoles.excludeRoles.includes(dbRole.rolname)) continue;
            if (!preparedRoles.includeRoles.includes(dbRole.rolname)) continue;
            rolesToReturn[dbRole.rolname] = {
              createDb: dbRole.rolcreatedb,
              createRole: dbRole.rolcreaterole,
              inherit: dbRole.rolinherit,
              name: dbRole.rolname
            };
          }
        }
      }
      const schemasForLinkedPoliciesInSchema = Object.values(tsSchema?.policies ?? {}).map((it) => it.schema);
      const wherePolicies = [...schemaFilters, ...schemasForLinkedPoliciesInSchema].map((t) => `schemaname = '${t}'`).join(" or ");
      const policiesByTable = {};
      const allPolicies = await db.query(`SELECT schemaname, tablename, policyname as name, permissive as "as", roles as to, cmd as for, qual as using, with_check as "withCheck" FROM pg_policies${wherePolicies === "" ? "" : ` WHERE ${wherePolicies}`};`);
      for (const dbPolicy of allPolicies) {
        const { tablename, schemaname, to, withCheck, using, ...rest } = dbPolicy;
        const tableForPolicy = policiesByTable[`${schemaname}.${tablename}`];
        const parsedTo = typeof to === "string" ? to.slice(1, -1).split(",") : to;
        const parsedWithCheck = withCheck === null ? void 0 : withCheck;
        const parsedUsing = using === null ? void 0 : using;
        if (tableForPolicy) {
          tableForPolicy[dbPolicy.name] = { ...rest, to: parsedTo };
        } else {
          policiesByTable[`${schemaname}.${tablename}`] = {
            [dbPolicy.name]: { ...rest, to: parsedTo, withCheck: parsedWithCheck, using: parsedUsing }
          };
        }
        if (tsSchema?.policies[dbPolicy.name]) {
          policies[dbPolicy.name] = {
            ...rest,
            to: parsedTo,
            withCheck: parsedWithCheck,
            using: parsedUsing,
            on: tsSchema?.policies[dbPolicy.name].on
          };
        }
      }
      if (progressCallback) {
        progressCallback(
          "policies",
          Object.values(policiesByTable).reduce((total, innerRecord) => {
            return total + Object.keys(innerRecord).length;
          }, 0),
          "done"
        );
      }
      const sequencesInColumns = [];
      const all = allTables.filter((it) => it.type === "table").map((row) => {
        return new Promise(async (res, rej) => {
          const tableName = row.table_name;
          if (!tablesFilter(tableName)) return res("");
          tableCount += 1;
          const tableSchema = row.table_schema;
          try {
            const columnToReturn = {};
            const indexToReturn = {};
            const foreignKeysToReturn = {};
            const primaryKeys = {};
            const uniqueConstrains = {};
            const checkConstraints = {};
            const tableResponse = await getColumnsInfoQuery({ schema: tableSchema, table: tableName, db });
            const tableConstraints = await db.query(
              `SELECT c.column_name, c.data_type, constraint_type, constraint_name, constraint_schema
      FROM information_schema.table_constraints tc
      JOIN information_schema.constraint_column_usage AS ccu USING (constraint_schema, constraint_name)
      JOIN information_schema.columns AS c ON c.table_schema = tc.constraint_schema
        AND tc.table_name = c.table_name AND ccu.column_name = c.column_name
      WHERE tc.table_name = '${tableName}' and constraint_schema = '${tableSchema}';`
            );
            const tableChecks = await db.query(`SELECT 
						tc.constraint_name,
						tc.constraint_type,
						pg_get_constraintdef(con.oid) AS constraint_definition
					FROM 
						information_schema.table_constraints AS tc
						JOIN pg_constraint AS con 
							ON tc.constraint_name = con.conname
							AND con.conrelid = (
								SELECT oid 
								FROM pg_class 
								WHERE relname = tc.table_name 
								AND relnamespace = (
									SELECT oid 
									FROM pg_namespace 
									WHERE nspname = tc.constraint_schema
								)
							)
					WHERE 
						tc.table_name = '${tableName}'
						AND tc.constraint_schema = '${tableSchema}'
						AND tc.constraint_type = 'CHECK';`);
            columnsCount += tableResponse.length;
            if (progressCallback) {
              progressCallback("columns", columnsCount, "fetching");
            }
            const tableForeignKeys = await db.query(
              `SELECT
            con.contype AS constraint_type,
            nsp.nspname AS constraint_schema,
            con.conname AS constraint_name,
            rel.relname AS table_name,
            att.attname AS column_name,
            fnsp.nspname AS foreign_table_schema,
            frel.relname AS foreign_table_name,
            fatt.attname AS foreign_column_name,
            CASE con.confupdtype
              WHEN 'a' THEN 'NO ACTION'
              WHEN 'r' THEN 'RESTRICT'
              WHEN 'n' THEN 'SET NULL'
              WHEN 'c' THEN 'CASCADE'
              WHEN 'd' THEN 'SET DEFAULT'
            END AS update_rule,
            CASE con.confdeltype
              WHEN 'a' THEN 'NO ACTION'
              WHEN 'r' THEN 'RESTRICT'
              WHEN 'n' THEN 'SET NULL'
              WHEN 'c' THEN 'CASCADE'
              WHEN 'd' THEN 'SET DEFAULT'
            END AS delete_rule
          FROM
            pg_catalog.pg_constraint con
            JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid
            JOIN pg_catalog.pg_namespace nsp ON nsp.oid = con.connamespace
            LEFT JOIN pg_catalog.pg_attribute att ON att.attnum = ANY (con.conkey)
              AND att.attrelid = con.conrelid
            LEFT JOIN pg_catalog.pg_class frel ON frel.oid = con.confrelid
            LEFT JOIN pg_catalog.pg_namespace fnsp ON fnsp.oid = frel.relnamespace
            LEFT JOIN pg_catalog.pg_attribute fatt ON fatt.attnum = ANY (con.confkey)
              AND fatt.attrelid = con.confrelid
          WHERE
            nsp.nspname = '${tableSchema}'
            AND rel.relname = '${tableName}'
            AND con.contype IN ('f');`
            );
            foreignKeysCount += tableForeignKeys.length;
            if (progressCallback) {
              progressCallback("fks", foreignKeysCount, "fetching");
            }
            for (const fk5 of tableForeignKeys) {
              const columnFrom = fk5.column_name;
              const tableTo = fk5.foreign_table_name;
              const columnTo = fk5.foreign_column_name;
              const schemaTo = fk5.foreign_table_schema;
              const foreignKeyName = fk5.constraint_name;
              const onUpdate = fk5.update_rule?.toLowerCase();
              const onDelete = fk5.delete_rule?.toLowerCase();
              if (typeof foreignKeysToReturn[foreignKeyName] !== "undefined") {
                foreignKeysToReturn[foreignKeyName].columnsFrom.push(columnFrom);
                foreignKeysToReturn[foreignKeyName].columnsTo.push(columnTo);
              } else {
                foreignKeysToReturn[foreignKeyName] = {
                  name: foreignKeyName,
                  tableFrom: tableName,
                  tableTo,
                  schemaTo,
                  columnsFrom: [columnFrom],
                  columnsTo: [columnTo],
                  onDelete,
                  onUpdate
                };
              }
              foreignKeysToReturn[foreignKeyName].columnsFrom = [
                ...new Set(foreignKeysToReturn[foreignKeyName].columnsFrom)
              ];
              foreignKeysToReturn[foreignKeyName].columnsTo = [...new Set(foreignKeysToReturn[foreignKeyName].columnsTo)];
            }
            const uniqueConstrainsRows = tableConstraints.filter((mapRow) => mapRow.constraint_type === "UNIQUE");
            for (const unqs of uniqueConstrainsRows) {
              const columnName = unqs.column_name;
              const constraintName = unqs.constraint_name;
              if (typeof uniqueConstrains[constraintName] !== "undefined") {
                uniqueConstrains[constraintName].columns.push(columnName);
              } else {
                uniqueConstrains[constraintName] = {
                  columns: [columnName],
                  nullsNotDistinct: false,
                  name: constraintName
                };
              }
            }
            checksCount += tableChecks.length;
            if (progressCallback) {
              progressCallback("checks", checksCount, "fetching");
            }
            for (const checks of tableChecks) {
              let checkValue = checks.constraint_definition;
              const constraintName = checks.constraint_name;
              checkValue = checkValue.replace(/^CHECK\s*\(\(/, "").replace(/\)\)\s*$/, "");
              checkConstraints[constraintName] = {
                name: constraintName,
                value: checkValue
              };
            }
            for (const columnResponse of tableResponse) {
              const columnName = columnResponse.column_name;
              const columnAdditionalDT = columnResponse.additional_dt;
              const columnDimensions = columnResponse.array_dimensions;
              const enumType2 = columnResponse.enum_name;
              let columnType = columnResponse.data_type;
              const typeSchema = columnResponse.type_schema;
              const defaultValueRes = columnResponse.column_default;
              const isGenerated = columnResponse.is_generated === "ALWAYS";
              const generationExpression = columnResponse.generation_expression;
              const isIdentity = columnResponse.is_identity === "YES";
              const identityGeneration = columnResponse.identity_generation === "ALWAYS" ? "always" : "byDefault";
              const identityStart = columnResponse.identity_start;
              const identityIncrement = columnResponse.identity_increment;
              const identityMaximum = columnResponse.identity_maximum;
              const identityMinimum = columnResponse.identity_minimum;
              const identityCycle = columnResponse.identity_cycle === "YES";
              const identityName = columnResponse.seq_name;
              const primaryKey = tableConstraints.filter(
                (mapRow) => columnName === mapRow.column_name && mapRow.constraint_type === "PRIMARY KEY"
              );
              const cprimaryKey = tableConstraints.filter((mapRow) => mapRow.constraint_type === "PRIMARY KEY");
              if (cprimaryKey.length > 1) {
                const tableCompositePkName = await db.query(
                  `SELECT conname AS primary_key
            FROM   pg_constraint join pg_class on (pg_class.oid = conrelid)
            WHERE  contype = 'p' 
            AND    connamespace = $1::regnamespace  
            AND    pg_class.relname = $2;`,
                  [tableSchema, tableName]
                );
                primaryKeys[tableCompositePkName[0].primary_key] = {
                  name: tableCompositePkName[0].primary_key,
                  columns: cprimaryKey.map((c) => c.column_name)
                };
              }
              let columnTypeMapped = columnType;
              if (columnAdditionalDT === "ARRAY") {
                if (typeof internals.tables[tableName] === "undefined") {
                  internals.tables[tableName] = {
                    columns: {
                      [columnName]: {
                        isArray: true,
                        dimensions: columnDimensions,
                        rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
                      }
                    }
                  };
                } else {
                  if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
                    internals.tables[tableName].columns[columnName] = {
                      isArray: true,
                      dimensions: columnDimensions,
                      rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
                    };
                  }
                }
              }
              const defaultValue = defaultForColumn(columnResponse, internals, tableName);
              if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
                if (typeof internals.tables[tableName] === "undefined") {
                  internals.tables[tableName] = {
                    columns: {
                      [columnName]: {
                        isDefaultAnExpression: true
                      }
                    }
                  };
                } else {
                  if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
                    internals.tables[tableName].columns[columnName] = {
                      isDefaultAnExpression: true
                    };
                  } else {
                    internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
                  }
                }
              }
              const isSerial = columnType === "serial";
              if (columnTypeMapped.startsWith("numeric(")) {
                columnTypeMapped = columnTypeMapped.replace(",", ", ");
              }
              if (columnAdditionalDT === "ARRAY") {
                for (let i = 1; i < Number(columnDimensions); i++) {
                  columnTypeMapped += "[]";
                }
              }
              columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
              columnTypeMapped = trimChar(columnTypeMapped, '"');
              columnToReturn[columnName] = {
                name: columnName,
                type: (
                  // filter vectors, but in future we should filter any extension that was installed by user
                  columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry", "halfvec", "sparsevec", "bit"].includes(enumType2) ? enumType2 : columnTypeMapped
                ),
                typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
                primaryKey: primaryKey.length === 1 && cprimaryKey.length < 2,
                // default: isSerial ? undefined : defaultValue,
                notNull: columnResponse.is_nullable === "NO",
                generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0,
                identity: isIdentity ? {
                  type: identityGeneration,
                  name: identityName,
                  increment: stringFromDatabaseIdentityProperty(identityIncrement),
                  minValue: stringFromDatabaseIdentityProperty(identityMinimum),
                  maxValue: stringFromDatabaseIdentityProperty(identityMaximum),
                  startWith: stringFromDatabaseIdentityProperty(identityStart),
                  cache: sequencesToReturn[identityName]?.cache ? sequencesToReturn[identityName]?.cache : sequencesToReturn[`${tableSchema}.${identityName}`]?.cache ? sequencesToReturn[`${tableSchema}.${identityName}`]?.cache : void 0,
                  cycle: identityCycle,
                  schema: tableSchema
                } : void 0
              };
              if (identityName && typeof identityName === "string") {
                delete sequencesToReturn[`${tableSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
                delete sequencesToReturn[identityName];
              }
              if (!isSerial && typeof defaultValue !== "undefined") {
                columnToReturn[columnName].default = defaultValue;
              }
            }
            const dbIndexes = await db.query(
              `SELECT  DISTINCT ON (t.relname, ic.relname, k.i) t.relname as table_name, ic.relname AS indexname,
        k.i AS index_order,
        i.indisunique as is_unique,
        am.amname as method,
        ic.reloptions as with,
        coalesce(a.attname, pg_get_indexdef(i.indexrelid, k.i, false)) AS column_name,
          CASE
        WHEN pg_get_expr(i.indexprs, i.indrelid) IS NOT NULL THEN 1
        ELSE 0
    END AS is_expression,
        i.indoption[k.i-1] & 1 = 1 AS descending,
        i.indoption[k.i-1] & 2 = 2 AS nulls_first,
        pg_get_expr(
                              i.indpred,
                              i.indrelid
                          ) as where,
         opc.opcname
      FROM pg_class t
          LEFT JOIN pg_index i ON t.oid = i.indrelid
          LEFT JOIN pg_class ic ON ic.oid = i.indexrelid
		  CROSS JOIN LATERAL (SELECT unnest(i.indkey), generate_subscripts(i.indkey, 1) + 1) AS k(attnum, i)
          LEFT JOIN pg_attribute AS a
            ON i.indrelid = a.attrelid AND k.attnum = a.attnum
          JOIN pg_namespace c on c.oid = t.relnamespace
        LEFT JOIN pg_am AS am ON ic.relam = am.oid
        JOIN pg_opclass opc ON opc.oid = ANY(i.indclass)
      WHERE
      c.nspname = '${tableSchema}' AND
      t.relname = '${tableName}';`
            );
            const dbIndexFromConstraint = await db.query(
              `SELECT
          idx.indexrelname AS index_name,
          idx.relname AS table_name,
          schemaname,
          CASE WHEN con.conname IS NOT NULL THEN 1 ELSE 0 END AS generated_by_constraint
        FROM
          pg_stat_user_indexes idx
        LEFT JOIN
          pg_constraint con ON con.conindid = idx.indexrelid
        WHERE idx.relname = '${tableName}' and schemaname = '${tableSchema}'
        group by index_name, table_name,schemaname, generated_by_constraint;`
            );
            const idxsInConsteraint = dbIndexFromConstraint.filter((it) => it.generated_by_constraint === 1).map(
              (it) => it.index_name
            );
            for (const dbIndex of dbIndexes) {
              const indexName2 = dbIndex.indexname;
              const indexColumnName = dbIndex.column_name;
              const indexIsUnique = dbIndex.is_unique;
              const indexMethod = dbIndex.method;
              const indexWith = dbIndex.with;
              const indexWhere = dbIndex.where;
              const opclass = dbIndex.opcname;
              const isExpression = dbIndex.is_expression === 1;
              const desc2 = dbIndex.descending;
              const nullsFirst = dbIndex.nulls_first;
              const mappedWith = {};
              if (indexWith !== null) {
                indexWith.forEach((it) => {
                  const splitted = it.split("=");
                  mappedWith[splitted[0]] = splitted[1];
                });
              }
              if (idxsInConsteraint.includes(indexName2)) continue;
              if (typeof indexToReturn[indexName2] !== "undefined") {
                indexToReturn[indexName2].columns.push({
                  expression: indexColumnName,
                  asc: !desc2,
                  nulls: nullsFirst ? "first" : "last",
                  opclass,
                  isExpression
                });
              } else {
                indexToReturn[indexName2] = {
                  name: indexName2,
                  columns: [
                    {
                      expression: indexColumnName,
                      asc: !desc2,
                      nulls: nullsFirst ? "first" : "last",
                      opclass,
                      isExpression
                    }
                  ],
                  isUnique: indexIsUnique,
                  // should not be a part of diff detects
                  concurrently: false,
                  method: indexMethod,
                  where: indexWhere === null ? void 0 : indexWhere,
                  with: mappedWith
                };
              }
            }
            indexesCount += Object.keys(indexToReturn).length;
            if (progressCallback) {
              progressCallback("indexes", indexesCount, "fetching");
            }
            result[`${tableSchema}.${tableName}`] = {
              name: tableName,
              schema: tableSchema !== "public" ? tableSchema : "",
              columns: columnToReturn,
              indexes: indexToReturn,
              foreignKeys: foreignKeysToReturn,
              compositePrimaryKeys: primaryKeys,
              uniqueConstraints: uniqueConstrains,
              checkConstraints,
              policies: policiesByTable[`${tableSchema}.${tableName}`] ?? {},
              isRLSEnabled: row.rls_enabled
            };
          } catch (e) {
            rej(e);
            return;
          }
          res("");
        });
      });
      if (progressCallback) {
        progressCallback("tables", tableCount, "done");
      }
      for await (const _2 of all) {
      }
      const allViews = allTables.filter((it) => it.type === "view" || it.type === "materialized_view").map((row) => {
        return new Promise(async (res, rej) => {
          const viewName = row.table_name;
          if (!tablesFilter(viewName)) return res("");
          tableCount += 1;
          const viewSchema = row.table_schema;
          try {
            const columnToReturn = {};
            const viewResponses = await getColumnsInfoQuery({ schema: viewSchema, table: viewName, db });
            for (const viewResponse of viewResponses) {
              const columnName = viewResponse.column_name;
              const columnAdditionalDT = viewResponse.additional_dt;
              const columnDimensions = viewResponse.array_dimensions;
              const enumType2 = viewResponse.enum_name;
              let columnType = viewResponse.data_type;
              const typeSchema = viewResponse.type_schema;
              const isGenerated = viewResponse.is_generated === "ALWAYS";
              const generationExpression = viewResponse.generation_expression;
              const isIdentity = viewResponse.is_identity === "YES";
              const identityGeneration = viewResponse.identity_generation === "ALWAYS" ? "always" : "byDefault";
              const identityStart = viewResponse.identity_start;
              const identityIncrement = viewResponse.identity_increment;
              const identityMaximum = viewResponse.identity_maximum;
              const identityMinimum = viewResponse.identity_minimum;
              const identityCycle = viewResponse.identity_cycle === "YES";
              const identityName = viewResponse.seq_name;
              const defaultValueRes = viewResponse.column_default;
              const primaryKey = viewResponse.constraint_type === "PRIMARY KEY";
              let columnTypeMapped = columnType;
              if (columnAdditionalDT === "ARRAY") {
                if (typeof internals.tables[viewName] === "undefined") {
                  internals.tables[viewName] = {
                    columns: {
                      [columnName]: {
                        isArray: true,
                        dimensions: columnDimensions,
                        rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
                      }
                    }
                  };
                } else {
                  if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
                    internals.tables[viewName].columns[columnName] = {
                      isArray: true,
                      dimensions: columnDimensions,
                      rawType: columnTypeMapped.substring(0, columnTypeMapped.length - 2)
                    };
                  }
                }
              }
              const defaultValue = defaultForColumn(viewResponse, internals, viewName);
              if (defaultValue === "NULL" || defaultValueRes && defaultValueRes.startsWith("(") && defaultValueRes.endsWith(")")) {
                if (typeof internals.tables[viewName] === "undefined") {
                  internals.tables[viewName] = {
                    columns: {
                      [columnName]: {
                        isDefaultAnExpression: true
                      }
                    }
                  };
                } else {
                  if (typeof internals.tables[viewName].columns[columnName] === "undefined") {
                    internals.tables[viewName].columns[columnName] = {
                      isDefaultAnExpression: true
                    };
                  } else {
                    internals.tables[viewName].columns[columnName].isDefaultAnExpression = true;
                  }
                }
              }
              const isSerial = columnType === "serial";
              if (columnTypeMapped.startsWith("numeric(")) {
                columnTypeMapped = columnTypeMapped.replace(",", ", ");
              }
              if (columnAdditionalDT === "ARRAY") {
                for (let i = 1; i < Number(columnDimensions); i++) {
                  columnTypeMapped += "[]";
                }
              }
              columnTypeMapped = columnTypeMapped.replace("character varying", "varchar").replace(" without time zone", "").replace("character", "char");
              columnTypeMapped = trimChar(columnTypeMapped, '"');
              columnToReturn[columnName] = {
                name: columnName,
                type: (
                  // filter vectors, but in future we should filter any extension that was installed by user
                  columnAdditionalDT === "USER-DEFINED" && !["vector", "geometry", "halfvec", "sparsevec", "bit"].includes(enumType2) ? enumType2 : columnTypeMapped
                ),
                typeSchema: enumsToReturn[`${typeSchema}.${enumType2}`] !== void 0 ? enumsToReturn[`${typeSchema}.${enumType2}`].schema : void 0,
                primaryKey,
                notNull: viewResponse.is_nullable === "NO",
                generated: isGenerated ? { as: generationExpression, type: "stored" } : void 0,
                identity: isIdentity ? {
                  type: identityGeneration,
                  name: identityName,
                  increment: stringFromDatabaseIdentityProperty(identityIncrement),
                  minValue: stringFromDatabaseIdentityProperty(identityMinimum),
                  maxValue: stringFromDatabaseIdentityProperty(identityMaximum),
                  startWith: stringFromDatabaseIdentityProperty(identityStart),
                  cache: sequencesToReturn[identityName]?.cache ? sequencesToReturn[identityName]?.cache : sequencesToReturn[`${viewSchema}.${identityName}`]?.cache ? sequencesToReturn[`${viewSchema}.${identityName}`]?.cache : void 0,
                  cycle: identityCycle,
                  schema: viewSchema
                } : void 0
              };
              if (identityName) {
                delete sequencesToReturn[`${viewSchema}.${identityName.startsWith('"') && identityName.endsWith('"') ? identityName.slice(1, -1) : identityName}`];
                delete sequencesToReturn[identityName];
              }
              if (!isSerial && typeof defaultValue !== "undefined") {
                columnToReturn[columnName].default = defaultValue;
              }
            }
            const [viewInfo] = await db.query(`
					SELECT
    c.relname AS view_name,
    n.nspname AS schema_name,
    pg_get_viewdef(c.oid, true) AS definition,
    ts.spcname AS tablespace_name,
    c.reloptions AS options,
    pg_tablespace_location(ts.oid) AS location
FROM
    pg_class c
JOIN
    pg_namespace n ON c.relnamespace = n.oid
LEFT JOIN
    pg_tablespace ts ON c.reltablespace = ts.oid 
WHERE
    (c.relkind = 'm' OR c.relkind = 'v')
    AND n.nspname = '${viewSchema}'
    AND c.relname = '${viewName}';`);
            const resultWith = {};
            if (viewInfo.options) {
              viewInfo.options.forEach((pair) => {
                const splitted = pair.split("=");
                const key = splitted[0];
                const value = splitted[1];
                if (value === "true") {
                  resultWith[key] = true;
                } else if (value === "false") {
                  resultWith[key] = false;
                } else if (!isNaN(Number(value))) {
                  resultWith[key] = Number(value);
                } else {
                  resultWith[key] = value;
                }
              });
            }
            const definition = viewInfo.definition.replace(/\s+/g, " ").replace(";", "").trim();
            const withOption = Object.values(resultWith).length ? Object.fromEntries(Object.entries(resultWith).map(([key, value]) => [key.camelCase(), value])) : void 0;
            const materialized = row.type === "materialized_view";
            views[`${viewSchema}.${viewName}`] = {
              name: viewName,
              schema: viewSchema,
              columns: columnToReturn,
              isExisting: false,
              definition,
              materialized,
              with: withOption,
              tablespace: viewInfo.tablespace_name ?? void 0
            };
          } catch (e) {
            rej(e);
            return;
          }
          res("");
        });
      });
      viewsCount = allViews.length;
      for await (const _2 of allViews) {
      }
      if (progressCallback) {
        progressCallback("columns", columnsCount, "done");
        progressCallback("indexes", indexesCount, "done");
        progressCallback("fks", foreignKeysCount, "done");
        progressCallback("checks", checksCount, "done");
        progressCallback("views", viewsCount, "done");
      }
      const schemasObject = Object.fromEntries([...schemas].map((it) => [it, it]));
      return {
        version: "7",
        dialect: "postgresql",
        tables: result,
        enums: enumsToReturn,
        schemas: schemasObject,
        sequences: sequencesToReturn,
        roles: rolesToReturn,
        policies,
        views,
        _meta: {
          schemas: {},
          tables: {},
          columns: {}
        },
        internal: internals
      };
    };
    defaultForColumn = (column6, internals, tableName) => {
      const columnName = column6.column_name;
      const isArray = internals?.tables[tableName]?.columns[columnName]?.isArray ?? false;
      if (column6.column_default === null || column6.column_default === void 0 || column6.data_type === "serial" || column6.data_type === "smallserial" || column6.data_type === "bigserial") {
        return void 0;
      }
      if (column6.column_default.endsWith("[]")) {
        column6.column_default = column6.column_default.slice(0, -2);
      }
      column6.column_default = column6.column_default.replace(/::(.*?)(?<![^\w"])(?=$)/, "");
      const columnDefaultAsString = column6.column_default.toString();
      if (isArray) {
        return `'{${columnDefaultAsString.slice(2, -2).split(/\s*,\s*/g).map((value) => {
          if (["integer", "smallint", "bigint", "double precision", "real"].includes(column6.data_type.slice(0, -2))) {
            return value;
          } else if (column6.data_type.startsWith("timestamp")) {
            return `${value}`;
          } else if (column6.data_type.slice(0, -2) === "interval") {
            return value.replaceAll('"', `"`);
          } else if (column6.data_type.slice(0, -2) === "boolean") {
            return value === "t" ? "true" : "false";
          } else if (["json", "jsonb"].includes(column6.data_type.slice(0, -2))) {
            return JSON.stringify(JSON.stringify(JSON.parse(JSON.parse(value)), null, 0));
          } else {
            return `"${value}"`;
          }
        }).join(",")}}'`;
      }
      if (["integer", "smallint", "bigint", "double precision", "real"].includes(column6.data_type)) {
        if (/^-?[\d.]+(?:e-?\d+)?$/.test(columnDefaultAsString)) {
          return Number(columnDefaultAsString);
        } else {
          if (typeof internals.tables[tableName] === "undefined") {
            internals.tables[tableName] = {
              columns: {
                [columnName]: {
                  isDefaultAnExpression: true
                }
              }
            };
          } else {
            if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
              internals.tables[tableName].columns[columnName] = {
                isDefaultAnExpression: true
              };
            } else {
              internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
            }
          }
          return columnDefaultAsString;
        }
      } else if (column6.data_type.includes("numeric")) {
        return columnDefaultAsString.includes("'") ? columnDefaultAsString : `'${columnDefaultAsString}'`;
      } else if (column6.data_type === "json" || column6.data_type === "jsonb") {
        const jsonWithoutSpaces = JSON.stringify(JSON.parse(columnDefaultAsString.slice(1, -1)));
        return `'${jsonWithoutSpaces}'::${column6.data_type}`;
      } else if (column6.data_type === "boolean") {
        return column6.column_default === "true";
      } else if (columnDefaultAsString === "NULL") {
        return `NULL`;
      } else if (columnDefaultAsString.startsWith("'") && columnDefaultAsString.endsWith("'")) {
        return columnDefaultAsString;
      } else {
        return `${columnDefaultAsString.replace(/\\/g, "`\\")}`;
      }
    };
    getColumnsInfoQuery = ({ schema: schema5, table: table6, db }) => {
      return db.query(
        `SELECT 
    a.attrelid::regclass::text AS table_name,  -- Table, view, or materialized view name
    a.attname AS column_name,   -- Column name
    CASE 
        WHEN NOT a.attisdropped THEN 
            CASE 
                WHEN a.attnotnull THEN 'NO'
                ELSE 'YES'
            END 
        ELSE NULL 
    END AS is_nullable,  -- NULL or NOT NULL constraint
    a.attndims AS array_dimensions,  -- Array dimensions
    CASE 
        WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[]) 
        AND EXISTS (
            SELECT FROM pg_attrdef ad
            WHERE ad.adrelid = a.attrelid 
            AND ad.adnum = a.attnum 
            AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval(''' 
                || pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)'
        )
        THEN CASE a.atttypid
            WHEN 'int'::regtype THEN 'serial'
            WHEN 'int8'::regtype THEN 'bigserial'
            WHEN 'int2'::regtype THEN 'smallserial'
        END
        ELSE format_type(a.atttypid, a.atttypmod)
    END AS data_type,  -- Column data type
--    ns.nspname AS type_schema,  -- Schema name
    pg_get_serial_sequence('"${schema5}"."${table6}"', a.attname)::regclass AS seq_name,  -- Serial sequence (if any)
    c.column_default,  -- Column default value
    c.data_type AS additional_dt,  -- Data type from information_schema
    c.udt_name AS enum_name,  -- Enum type (if applicable)
    c.is_generated,  -- Is it a generated column?
    c.generation_expression,  -- Generation expression (if generated)
    c.is_identity,  -- Is it an identity column?
    c.identity_generation,  -- Identity generation strategy (ALWAYS or BY DEFAULT)
    c.identity_start,  -- Start value of identity column
    c.identity_increment,  -- Increment for identity column
    c.identity_maximum,  -- Maximum value for identity column
    c.identity_minimum,  -- Minimum value for identity column
    c.identity_cycle,  -- Does the identity column cycle?
    enum_ns.nspname AS type_schema  -- Schema of the enum type
FROM 
    pg_attribute a
JOIN 
    pg_class cls ON cls.oid = a.attrelid  -- Join pg_class to get table/view/materialized view info
JOIN 
    pg_namespace ns ON ns.oid = cls.relnamespace  -- Join namespace to get schema info
LEFT JOIN 
    information_schema.columns c ON c.column_name = a.attname 
        AND c.table_schema = ns.nspname 
        AND c.table_name = cls.relname  -- Match schema and table/view name
LEFT JOIN 
    pg_type enum_t ON enum_t.oid = a.atttypid  -- Join to get the type info
LEFT JOIN 
    pg_namespace enum_ns ON enum_ns.oid = enum_t.typnamespace  -- Join to get the enum schema
WHERE 
    a.attnum > 0  -- Valid column numbers only
    AND NOT a.attisdropped  -- Skip dropped columns
    AND cls.relkind IN ('r', 'v', 'm')  -- Include regular tables ('r'), views ('v'), and materialized views ('m')
    AND ns.nspname = '${schema5}'  -- Filter by schema
    AND cls.relname = '${table6}'  -- Filter by table name
ORDER BY 
    a.attnum;  -- Order by column number`
      );
    };
  }
});

// src/cli/selector-ui.ts
var import_hanji4, Select;
var init_selector_ui = __esm({
  "src/cli/selector-ui.ts"() {
    "use strict";
    init_source();
    import_hanji4 = __toESM(require_hanji());
    Select = class extends import_hanji4.Prompt {
      constructor(items) {
        super();
        this.on("attach", (terminal) => terminal.toggleCursor("hide"));
        this.on("detach", (terminal) => terminal.toggleCursor("show"));
        this.data = new import_hanji4.SelectState(
          items.map((it) => ({ label: it, value: `${it}-value` }))
        );
        this.data.bind(this);
      }
      render(status) {
        if (status === "submitted" || status === "aborted") return "";
        let text5 = ``;
        this.data.items.forEach((it, idx) => {
          text5 += idx === this.data.selectedIdx ? `${source_default.green("\u276F " + it.label)}` : `  ${it.label}`;
          text5 += idx != this.data.items.length - 1 ? "\n" : "";
        });
        return text5;
      }
      result() {
        return {
          index: this.data.selectedIdx,
          value: this.data.items[this.data.selectedIdx].value
        };
      }
    };
  }
});

// ../drizzle-orm/dist/sqlite-core/alias.js
var init_alias3 = __esm({
  "../drizzle-orm/dist/sqlite-core/alias.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/sqlite-core/checks.js
var _a170, CheckBuilder2, _a171, Check2;
var init_checks2 = __esm({
  "../drizzle-orm/dist/sqlite-core/checks.js"() {
    "use strict";
    init_entity();
    _a170 = entityKind;
    CheckBuilder2 = class {
      constructor(name2, value) {
        __publicField(this, "brand");
        this.name = name2;
        this.value = value;
      }
      build(table6) {
        return new Check2(table6, this);
      }
    };
    __publicField(CheckBuilder2, _a170, "SQLiteCheckBuilder");
    _a171 = entityKind;
    Check2 = class {
      constructor(table6, builder) {
        __publicField(this, "name");
        __publicField(this, "value");
        this.table = table6;
        this.name = builder.name;
        this.value = builder.value;
      }
    };
    __publicField(Check2, _a171, "SQLiteCheck");
  }
});

// ../drizzle-orm/dist/sqlite-core/foreign-keys.js
var _a172, ForeignKeyBuilder2, _a173, ForeignKey2;
var init_foreign_keys2 = __esm({
  "../drizzle-orm/dist/sqlite-core/foreign-keys.js"() {
    "use strict";
    init_entity();
    init_table_utils();
    _a172 = entityKind;
    ForeignKeyBuilder2 = class {
      constructor(config, actions) {
        /** @internal */
        __publicField(this, "reference");
        /** @internal */
        __publicField(this, "_onUpdate");
        /** @internal */
        __publicField(this, "_onDelete");
        this.reference = () => {
          const { name: name2, columns, foreignColumns } = config();
          return { name: name2, columns, foreignTable: foreignColumns[0].table, foreignColumns };
        };
        if (actions) {
          this._onUpdate = actions.onUpdate;
          this._onDelete = actions.onDelete;
        }
      }
      onUpdate(action) {
        this._onUpdate = action;
        return this;
      }
      onDelete(action) {
        this._onDelete = action;
        return this;
      }
      /** @internal */
      build(table6) {
        return new ForeignKey2(table6, this);
      }
    };
    __publicField(ForeignKeyBuilder2, _a172, "SQLiteForeignKeyBuilder");
    _a173 = entityKind;
    ForeignKey2 = class {
      constructor(table6, builder) {
        __publicField(this, "reference");
        __publicField(this, "onUpdate");
        __publicField(this, "onDelete");
        this.table = table6;
        this.reference = builder.reference;
        this.onUpdate = builder._onUpdate;
        this.onDelete = builder._onDelete;
      }
      getName() {
        const { name: name2, columns, foreignColumns } = this.reference();
        const columnNames = columns.map((column6) => column6.name);
        const foreignColumnNames = foreignColumns.map((column6) => column6.name);
        const chunks = [
          this.table[TableName],
          ...columnNames,
          foreignColumns[0].table[TableName],
          ...foreignColumnNames
        ];
        return name2 ?? `${chunks.join("_")}_fk`;
      }
    };
    __publicField(ForeignKey2, _a173, "SQLiteForeignKey");
  }
});

// ../drizzle-orm/dist/sqlite-core/unique-constraint.js
function uniqueKeyName2(table6, columns) {
  return `${table6[TableName]}_${columns.join("_")}_unique`;
}
var _a174, UniqueConstraintBuilder2, _a175, UniqueOnConstraintBuilder2, _a176, UniqueConstraint2;
var init_unique_constraint2 = __esm({
  "../drizzle-orm/dist/sqlite-core/unique-constraint.js"() {
    "use strict";
    init_entity();
    init_table_utils();
    _a174 = entityKind;
    UniqueConstraintBuilder2 = class {
      constructor(columns, name2) {
        /** @internal */
        __publicField(this, "columns");
        this.name = name2;
        this.columns = columns;
      }
      /** @internal */
      build(table6) {
        return new UniqueConstraint2(table6, this.columns, this.name);
      }
    };
    __publicField(UniqueConstraintBuilder2, _a174, "SQLiteUniqueConstraintBuilder");
    _a175 = entityKind;
    UniqueOnConstraintBuilder2 = class {
      constructor(name2) {
        /** @internal */
        __publicField(this, "name");
        this.name = name2;
      }
      on(...columns) {
        return new UniqueConstraintBuilder2(columns, this.name);
      }
    };
    __publicField(UniqueOnConstraintBuilder2, _a175, "SQLiteUniqueOnConstraintBuilder");
    _a176 = entityKind;
    UniqueConstraint2 = class {
      constructor(table6, columns, name2) {
        __publicField(this, "columns");
        __publicField(this, "name");
        this.table = table6;
        this.columns = columns;
        this.name = name2 ?? uniqueKeyName2(this.table, this.columns.map((column6) => column6.name));
      }
      getName() {
        return this.name;
      }
    };
    __publicField(UniqueConstraint2, _a176, "SQLiteUniqueConstraint");
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/common.js
var _a177, _b121, SQLiteColumnBuilder, _a178, _b122, SQLiteColumn;
var init_common3 = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/common.js"() {
    "use strict";
    init_column_builder();
    init_column();
    init_entity();
    init_foreign_keys2();
    init_unique_constraint2();
    SQLiteColumnBuilder = class extends (_b121 = ColumnBuilder, _a177 = entityKind, _b121) {
      constructor() {
        super(...arguments);
        __publicField(this, "foreignKeyConfigs", []);
      }
      references(ref, actions = {}) {
        this.foreignKeyConfigs.push({ ref, actions });
        return this;
      }
      unique(name2) {
        this.config.isUnique = true;
        this.config.uniqueName = name2;
        return this;
      }
      generatedAlwaysAs(as, config) {
        this.config.generated = {
          as,
          type: "always",
          mode: config?.mode ?? "virtual"
        };
        return this;
      }
      /** @internal */
      buildForeignKeys(column6, table6) {
        return this.foreignKeyConfigs.map(({ ref, actions }) => {
          return ((ref2, actions2) => {
            const builder = new ForeignKeyBuilder2(() => {
              const foreignColumn = ref2();
              return { columns: [column6], foreignColumns: [foreignColumn] };
            });
            if (actions2.onUpdate) {
              builder.onUpdate(actions2.onUpdate);
            }
            if (actions2.onDelete) {
              builder.onDelete(actions2.onDelete);
            }
            return builder.build(table6);
          })(ref, actions);
        });
      }
    };
    __publicField(SQLiteColumnBuilder, _a177, "SQLiteColumnBuilder");
    SQLiteColumn = class extends (_b122 = Column2, _a178 = entityKind, _b122) {
      constructor(table6, config) {
        if (!config.uniqueName) {
          config.uniqueName = uniqueKeyName2(table6, [config.name]);
        }
        super(table6, config);
        this.table = table6;
      }
    };
    __publicField(SQLiteColumn, _a178, "SQLiteColumn");
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/blob.js
function blob(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config?.mode === "json") {
    return new SQLiteBlobJsonBuilder(name2);
  }
  if (config?.mode === "bigint") {
    return new SQLiteBigIntBuilder(name2);
  }
  return new SQLiteBlobBufferBuilder(name2);
}
var _a179, _b123, SQLiteBigIntBuilder, _a180, _b124, SQLiteBigInt, _a181, _b125, SQLiteBlobJsonBuilder, _a182, _b126, SQLiteBlobJson, _a183, _b127, SQLiteBlobBufferBuilder, _a184, _b128, SQLiteBlobBuffer;
var init_blob = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/blob.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common3();
    SQLiteBigIntBuilder = class extends (_b123 = SQLiteColumnBuilder, _a179 = entityKind, _b123) {
      constructor(name2) {
        super(name2, "bigint", "SQLiteBigInt");
      }
      /** @internal */
      build(table6) {
        return new SQLiteBigInt(table6, this.config);
      }
    };
    __publicField(SQLiteBigIntBuilder, _a179, "SQLiteBigIntBuilder");
    SQLiteBigInt = class extends (_b124 = SQLiteColumn, _a180 = entityKind, _b124) {
      getSQLType() {
        return "blob";
      }
      mapFromDriverValue(value) {
        if (Buffer.isBuffer(value)) {
          return BigInt(value.toString());
        }
        if (value instanceof ArrayBuffer) {
          const decoder = new TextDecoder();
          return BigInt(decoder.decode(value));
        }
        return BigInt(String.fromCodePoint(...value));
      }
      mapToDriverValue(value) {
        return Buffer.from(value.toString());
      }
    };
    __publicField(SQLiteBigInt, _a180, "SQLiteBigInt");
    SQLiteBlobJsonBuilder = class extends (_b125 = SQLiteColumnBuilder, _a181 = entityKind, _b125) {
      constructor(name2) {
        super(name2, "json", "SQLiteBlobJson");
      }
      /** @internal */
      build(table6) {
        return new SQLiteBlobJson(
          table6,
          this.config
        );
      }
    };
    __publicField(SQLiteBlobJsonBuilder, _a181, "SQLiteBlobJsonBuilder");
    SQLiteBlobJson = class extends (_b126 = SQLiteColumn, _a182 = entityKind, _b126) {
      getSQLType() {
        return "blob";
      }
      mapFromDriverValue(value) {
        if (Buffer.isBuffer(value)) {
          return JSON.parse(value.toString());
        }
        if (value instanceof ArrayBuffer) {
          const decoder = new TextDecoder();
          return JSON.parse(decoder.decode(value));
        }
        return JSON.parse(String.fromCodePoint(...value));
      }
      mapToDriverValue(value) {
        return Buffer.from(JSON.stringify(value));
      }
    };
    __publicField(SQLiteBlobJson, _a182, "SQLiteBlobJson");
    SQLiteBlobBufferBuilder = class extends (_b127 = SQLiteColumnBuilder, _a183 = entityKind, _b127) {
      constructor(name2) {
        super(name2, "buffer", "SQLiteBlobBuffer");
      }
      /** @internal */
      build(table6) {
        return new SQLiteBlobBuffer(table6, this.config);
      }
    };
    __publicField(SQLiteBlobBufferBuilder, _a183, "SQLiteBlobBufferBuilder");
    SQLiteBlobBuffer = class extends (_b128 = SQLiteColumn, _a184 = entityKind, _b128) {
      mapFromDriverValue(value) {
        if (Buffer.isBuffer(value)) {
          return value;
        }
        return Buffer.from(value);
      }
      getSQLType() {
        return "blob";
      }
    };
    __publicField(SQLiteBlobBuffer, _a184, "SQLiteBlobBuffer");
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/custom.js
function customType2(customTypeParams) {
  return (a, b) => {
    const { name: name2, config } = getColumnNameAndConfig(a, b);
    return new SQLiteCustomColumnBuilder(
      name2,
      config,
      customTypeParams
    );
  };
}
var _a185, _b129, SQLiteCustomColumnBuilder, _a186, _b130, SQLiteCustomColumn;
var init_custom2 = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/custom.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common3();
    SQLiteCustomColumnBuilder = class extends (_b129 = SQLiteColumnBuilder, _a185 = entityKind, _b129) {
      constructor(name2, fieldConfig, customTypeParams) {
        super(name2, "custom", "SQLiteCustomColumn");
        this.config.fieldConfig = fieldConfig;
        this.config.customTypeParams = customTypeParams;
      }
      /** @internal */
      build(table6) {
        return new SQLiteCustomColumn(
          table6,
          this.config
        );
      }
    };
    __publicField(SQLiteCustomColumnBuilder, _a185, "SQLiteCustomColumnBuilder");
    SQLiteCustomColumn = class extends (_b130 = SQLiteColumn, _a186 = entityKind, _b130) {
      constructor(table6, config) {
        super(table6, config);
        __publicField(this, "sqlName");
        __publicField(this, "mapTo");
        __publicField(this, "mapFrom");
        this.sqlName = config.customTypeParams.dataType(config.fieldConfig);
        this.mapTo = config.customTypeParams.toDriver;
        this.mapFrom = config.customTypeParams.fromDriver;
      }
      getSQLType() {
        return this.sqlName;
      }
      mapFromDriverValue(value) {
        return typeof this.mapFrom === "function" ? this.mapFrom(value) : value;
      }
      mapToDriverValue(value) {
        return typeof this.mapTo === "function" ? this.mapTo(value) : value;
      }
    };
    __publicField(SQLiteCustomColumn, _a186, "SQLiteCustomColumn");
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/integer.js
function integer2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config?.mode === "timestamp" || config?.mode === "timestamp_ms") {
    return new SQLiteTimestampBuilder(name2, config.mode);
  }
  if (config?.mode === "boolean") {
    return new SQLiteBooleanBuilder(name2, config.mode);
  }
  return new SQLiteIntegerBuilder(name2);
}
var _a187, _b131, SQLiteBaseIntegerBuilder, _a188, _b132, SQLiteBaseInteger, _a189, _b133, SQLiteIntegerBuilder, _a190, _b134, SQLiteInteger, _a191, _b135, SQLiteTimestampBuilder, _a192, _b136, SQLiteTimestamp, _a193, _b137, SQLiteBooleanBuilder, _a194, _b138, SQLiteBoolean;
var init_integer2 = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/integer.js"() {
    "use strict";
    init_entity();
    init_sql();
    init_utils2();
    init_common3();
    SQLiteBaseIntegerBuilder = class extends (_b131 = SQLiteColumnBuilder, _a187 = entityKind, _b131) {
      constructor(name2, dataType, columnType) {
        super(name2, dataType, columnType);
        this.config.autoIncrement = false;
      }
      primaryKey(config) {
        if (config?.autoIncrement) {
          this.config.autoIncrement = true;
        }
        this.config.hasDefault = true;
        return super.primaryKey();
      }
    };
    __publicField(SQLiteBaseIntegerBuilder, _a187, "SQLiteBaseIntegerBuilder");
    SQLiteBaseInteger = class extends (_b132 = SQLiteColumn, _a188 = entityKind, _b132) {
      constructor() {
        super(...arguments);
        __publicField(this, "autoIncrement", this.config.autoIncrement);
      }
      getSQLType() {
        return "integer";
      }
    };
    __publicField(SQLiteBaseInteger, _a188, "SQLiteBaseInteger");
    SQLiteIntegerBuilder = class extends (_b133 = SQLiteBaseIntegerBuilder, _a189 = entityKind, _b133) {
      constructor(name2) {
        super(name2, "number", "SQLiteInteger");
      }
      build(table6) {
        return new SQLiteInteger(
          table6,
          this.config
        );
      }
    };
    __publicField(SQLiteIntegerBuilder, _a189, "SQLiteIntegerBuilder");
    SQLiteInteger = class extends (_b134 = SQLiteBaseInteger, _a190 = entityKind, _b134) {
    };
    __publicField(SQLiteInteger, _a190, "SQLiteInteger");
    SQLiteTimestampBuilder = class extends (_b135 = SQLiteBaseIntegerBuilder, _a191 = entityKind, _b135) {
      constructor(name2, mode) {
        super(name2, "date", "SQLiteTimestamp");
        this.config.mode = mode;
      }
      /**
       * @deprecated Use `default()` with your own expression instead.
       *
       * Adds `DEFAULT (cast((julianday('now') - 2440587.5)*86400000 as integer))` to the column, which is the current epoch timestamp in milliseconds.
       */
      defaultNow() {
        return this.default(sql`(cast((julianday('now') - 2440587.5)*86400000 as integer))`);
      }
      build(table6) {
        return new SQLiteTimestamp(
          table6,
          this.config
        );
      }
    };
    __publicField(SQLiteTimestampBuilder, _a191, "SQLiteTimestampBuilder");
    SQLiteTimestamp = class extends (_b136 = SQLiteBaseInteger, _a192 = entityKind, _b136) {
      constructor() {
        super(...arguments);
        __publicField(this, "mode", this.config.mode);
      }
      mapFromDriverValue(value) {
        if (this.config.mode === "timestamp") {
          return new Date(value * 1e3);
        }
        return new Date(value);
      }
      mapToDriverValue(value) {
        const unix = value.getTime();
        if (this.config.mode === "timestamp") {
          return Math.floor(unix / 1e3);
        }
        return unix;
      }
    };
    __publicField(SQLiteTimestamp, _a192, "SQLiteTimestamp");
    SQLiteBooleanBuilder = class extends (_b137 = SQLiteBaseIntegerBuilder, _a193 = entityKind, _b137) {
      constructor(name2, mode) {
        super(name2, "boolean", "SQLiteBoolean");
        this.config.mode = mode;
      }
      build(table6) {
        return new SQLiteBoolean(
          table6,
          this.config
        );
      }
    };
    __publicField(SQLiteBooleanBuilder, _a193, "SQLiteBooleanBuilder");
    SQLiteBoolean = class extends (_b138 = SQLiteBaseInteger, _a194 = entityKind, _b138) {
      constructor() {
        super(...arguments);
        __publicField(this, "mode", this.config.mode);
      }
      mapFromDriverValue(value) {
        return Number(value) === 1;
      }
      mapToDriverValue(value) {
        return value ? 1 : 0;
      }
    };
    __publicField(SQLiteBoolean, _a194, "SQLiteBoolean");
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/numeric.js
function numeric2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  const mode = config?.mode;
  return mode === "number" ? new SQLiteNumericNumberBuilder(name2) : mode === "bigint" ? new SQLiteNumericBigIntBuilder(name2) : new SQLiteNumericBuilder(name2);
}
var _a195, _b139, SQLiteNumericBuilder, _a196, _b140, SQLiteNumeric, _a197, _b141, SQLiteNumericNumberBuilder, _a198, _b142, SQLiteNumericNumber, _a199, _b143, SQLiteNumericBigIntBuilder, _a200, _b144, SQLiteNumericBigInt;
var init_numeric2 = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/numeric.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common3();
    SQLiteNumericBuilder = class extends (_b139 = SQLiteColumnBuilder, _a195 = entityKind, _b139) {
      constructor(name2) {
        super(name2, "string", "SQLiteNumeric");
      }
      /** @internal */
      build(table6) {
        return new SQLiteNumeric(
          table6,
          this.config
        );
      }
    };
    __publicField(SQLiteNumericBuilder, _a195, "SQLiteNumericBuilder");
    SQLiteNumeric = class extends (_b140 = SQLiteColumn, _a196 = entityKind, _b140) {
      mapFromDriverValue(value) {
        if (typeof value === "string") return value;
        return String(value);
      }
      getSQLType() {
        return "numeric";
      }
    };
    __publicField(SQLiteNumeric, _a196, "SQLiteNumeric");
    SQLiteNumericNumberBuilder = class extends (_b141 = SQLiteColumnBuilder, _a197 = entityKind, _b141) {
      constructor(name2) {
        super(name2, "number", "SQLiteNumericNumber");
      }
      /** @internal */
      build(table6) {
        return new SQLiteNumericNumber(
          table6,
          this.config
        );
      }
    };
    __publicField(SQLiteNumericNumberBuilder, _a197, "SQLiteNumericNumberBuilder");
    SQLiteNumericNumber = class extends (_b142 = SQLiteColumn, _a198 = entityKind, _b142) {
      constructor() {
        super(...arguments);
        __publicField(this, "mapToDriverValue", String);
      }
      mapFromDriverValue(value) {
        if (typeof value === "number") return value;
        return Number(value);
      }
      getSQLType() {
        return "numeric";
      }
    };
    __publicField(SQLiteNumericNumber, _a198, "SQLiteNumericNumber");
    SQLiteNumericBigIntBuilder = class extends (_b143 = SQLiteColumnBuilder, _a199 = entityKind, _b143) {
      constructor(name2) {
        super(name2, "bigint", "SQLiteNumericBigInt");
      }
      /** @internal */
      build(table6) {
        return new SQLiteNumericBigInt(
          table6,
          this.config
        );
      }
    };
    __publicField(SQLiteNumericBigIntBuilder, _a199, "SQLiteNumericBigIntBuilder");
    SQLiteNumericBigInt = class extends (_b144 = SQLiteColumn, _a200 = entityKind, _b144) {
      constructor() {
        super(...arguments);
        __publicField(this, "mapFromDriverValue", BigInt);
        __publicField(this, "mapToDriverValue", String);
      }
      getSQLType() {
        return "numeric";
      }
    };
    __publicField(SQLiteNumericBigInt, _a200, "SQLiteNumericBigInt");
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/real.js
function real2(name2) {
  return new SQLiteRealBuilder(name2 ?? "");
}
var _a201, _b145, SQLiteRealBuilder, _a202, _b146, SQLiteReal;
var init_real2 = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/real.js"() {
    "use strict";
    init_entity();
    init_common3();
    SQLiteRealBuilder = class extends (_b145 = SQLiteColumnBuilder, _a201 = entityKind, _b145) {
      constructor(name2) {
        super(name2, "number", "SQLiteReal");
      }
      /** @internal */
      build(table6) {
        return new SQLiteReal(table6, this.config);
      }
    };
    __publicField(SQLiteRealBuilder, _a201, "SQLiteRealBuilder");
    SQLiteReal = class extends (_b146 = SQLiteColumn, _a202 = entityKind, _b146) {
      getSQLType() {
        return "real";
      }
    };
    __publicField(SQLiteReal, _a202, "SQLiteReal");
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/text.js
function text2(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config.mode === "json") {
    return new SQLiteTextJsonBuilder(name2);
  }
  return new SQLiteTextBuilder(name2, config);
}
var _a203, _b147, SQLiteTextBuilder, _a204, _b148, SQLiteText, _a205, _b149, SQLiteTextJsonBuilder, _a206, _b150, SQLiteTextJson;
var init_text2 = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/text.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common3();
    SQLiteTextBuilder = class extends (_b147 = SQLiteColumnBuilder, _a203 = entityKind, _b147) {
      constructor(name2, config) {
        super(name2, "string", "SQLiteText");
        this.config.enumValues = config.enum;
        this.config.length = config.length;
      }
      /** @internal */
      build(table6) {
        return new SQLiteText(
          table6,
          this.config
        );
      }
    };
    __publicField(SQLiteTextBuilder, _a203, "SQLiteTextBuilder");
    SQLiteText = class extends (_b148 = SQLiteColumn, _a204 = entityKind, _b148) {
      constructor(table6, config) {
        super(table6, config);
        __publicField(this, "enumValues", this.config.enumValues);
        __publicField(this, "length", this.config.length);
      }
      getSQLType() {
        return `text${this.config.length ? `(${this.config.length})` : ""}`;
      }
    };
    __publicField(SQLiteText, _a204, "SQLiteText");
    SQLiteTextJsonBuilder = class extends (_b149 = SQLiteColumnBuilder, _a205 = entityKind, _b149) {
      constructor(name2) {
        super(name2, "json", "SQLiteTextJson");
      }
      /** @internal */
      build(table6) {
        return new SQLiteTextJson(
          table6,
          this.config
        );
      }
    };
    __publicField(SQLiteTextJsonBuilder, _a205, "SQLiteTextJsonBuilder");
    SQLiteTextJson = class extends (_b150 = SQLiteColumn, _a206 = entityKind, _b150) {
      getSQLType() {
        return "text";
      }
      mapFromDriverValue(value) {
        return JSON.parse(value);
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
    };
    __publicField(SQLiteTextJson, _a206, "SQLiteTextJson");
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/index.js
var init_columns2 = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/index.js"() {
    "use strict";
    init_blob();
    init_common3();
    init_custom2();
    init_integer2();
    init_numeric2();
    init_real2();
    init_text2();
  }
});

// ../drizzle-orm/dist/sqlite-core/columns/all.js
function getSQLiteColumnBuilders() {
  return {
    blob,
    customType: customType2,
    integer: integer2,
    numeric: numeric2,
    real: real2,
    text: text2
  };
}
var init_all2 = __esm({
  "../drizzle-orm/dist/sqlite-core/columns/all.js"() {
    "use strict";
    init_blob();
    init_custom2();
    init_integer2();
    init_numeric2();
    init_real2();
    init_text2();
  }
});

// ../drizzle-orm/dist/sqlite-core/table.js
function sqliteTableBase(name2, columns, extraConfig, schema5, baseName = name2) {
  const rawTable = new SQLiteTable(name2, schema5, baseName);
  const parsedColumns = typeof columns === "function" ? columns(getSQLiteColumnBuilders()) : columns;
  const builtColumns = Object.fromEntries(
    Object.entries(parsedColumns).map(([name22, colBuilderBase]) => {
      const colBuilder = colBuilderBase;
      colBuilder.setName(name22);
      const column6 = colBuilder.build(rawTable);
      rawTable[InlineForeignKeys2].push(...colBuilder.buildForeignKeys(column6, rawTable));
      return [name22, column6];
    })
  );
  const table6 = Object.assign(rawTable, builtColumns);
  table6[Table2.Symbol.Columns] = builtColumns;
  table6[Table2.Symbol.ExtraConfigColumns] = builtColumns;
  if (extraConfig) {
    table6[SQLiteTable.Symbol.ExtraConfigBuilder] = extraConfig;
  }
  return table6;
}
var InlineForeignKeys2, _a207, _b151, _c7, _d3, _e3, SQLiteTable, sqliteTable;
var init_table3 = __esm({
  "../drizzle-orm/dist/sqlite-core/table.js"() {
    "use strict";
    init_entity();
    init_table();
    init_all2();
    InlineForeignKeys2 = Symbol.for("drizzle:SQLiteInlineForeignKeys");
    SQLiteTable = class extends (_e3 = Table2, _d3 = entityKind, _c7 = Table2.Symbol.Columns, _b151 = InlineForeignKeys2, _a207 = Table2.Symbol.ExtraConfigBuilder, _e3) {
      constructor() {
        super(...arguments);
        /** @internal */
        __publicField(this, _c7);
        /** @internal */
        __publicField(this, _b151, []);
        /** @internal */
        __publicField(this, _a207);
      }
    };
    __publicField(SQLiteTable, _d3, "SQLiteTable");
    /** @internal */
    __publicField(SQLiteTable, "Symbol", Object.assign({}, Table2.Symbol, {
      InlineForeignKeys: InlineForeignKeys2
    }));
    sqliteTable = (name2, columns, extraConfig) => {
      return sqliteTableBase(name2, columns, extraConfig);
    };
  }
});

// ../drizzle-orm/dist/sqlite-core/indexes.js
var _a208, IndexBuilderOn2, _a209, IndexBuilder2, _a210, Index4;
var init_indexes2 = __esm({
  "../drizzle-orm/dist/sqlite-core/indexes.js"() {
    "use strict";
    init_entity();
    _a208 = entityKind;
    IndexBuilderOn2 = class {
      constructor(name2, unique) {
        this.name = name2;
        this.unique = unique;
      }
      on(...columns) {
        return new IndexBuilder2(this.name, columns, this.unique);
      }
    };
    __publicField(IndexBuilderOn2, _a208, "SQLiteIndexBuilderOn");
    _a209 = entityKind;
    IndexBuilder2 = class {
      constructor(name2, columns, unique) {
        /** @internal */
        __publicField(this, "config");
        this.config = {
          name: name2,
          columns,
          unique,
          where: void 0
        };
      }
      /**
       * Condition for partial index.
       */
      where(condition) {
        this.config.where = condition;
        return this;
      }
      /** @internal */
      build(table6) {
        return new Index4(this.config, table6);
      }
    };
    __publicField(IndexBuilder2, _a209, "SQLiteIndexBuilder");
    _a210 = entityKind;
    Index4 = class {
      constructor(config, table6) {
        __publicField(this, "config");
        this.config = { ...config, table: table6 };
      }
    };
    __publicField(Index4, _a210, "SQLiteIndex");
  }
});

// ../drizzle-orm/dist/sqlite-core/primary-keys.js
var _a211, PrimaryKeyBuilder2, _a212, PrimaryKey2;
var init_primary_keys2 = __esm({
  "../drizzle-orm/dist/sqlite-core/primary-keys.js"() {
    "use strict";
    init_entity();
    init_table3();
    _a211 = entityKind;
    PrimaryKeyBuilder2 = class {
      constructor(columns, name2) {
        /** @internal */
        __publicField(this, "columns");
        /** @internal */
        __publicField(this, "name");
        this.columns = columns;
        this.name = name2;
      }
      /** @internal */
      build(table6) {
        return new PrimaryKey2(table6, this.columns, this.name);
      }
    };
    __publicField(PrimaryKeyBuilder2, _a211, "SQLitePrimaryKeyBuilder");
    _a212 = entityKind;
    PrimaryKey2 = class {
      constructor(table6, columns, name2) {
        __publicField(this, "columns");
        __publicField(this, "name");
        this.table = table6;
        this.columns = columns;
        this.name = name2;
      }
      getName() {
        return this.name ?? `${this.table[SQLiteTable.Symbol.Name]}_${this.columns.map((column6) => column6.name).join("_")}_pk`;
      }
    };
    __publicField(PrimaryKey2, _a212, "SQLitePrimaryKey");
  }
});

// ../drizzle-orm/dist/sqlite-core/utils.js
function getTableConfig2(table6) {
  const columns = Object.values(table6[SQLiteTable.Symbol.Columns]);
  const indexes = [];
  const checks = [];
  const primaryKeys = [];
  const uniqueConstraints = [];
  const foreignKeys = Object.values(table6[SQLiteTable.Symbol.InlineForeignKeys]);
  const name2 = table6[Table2.Symbol.Name];
  const extraConfigBuilder = table6[SQLiteTable.Symbol.ExtraConfigBuilder];
  if (extraConfigBuilder !== void 0) {
    const extraConfig = extraConfigBuilder(table6[SQLiteTable.Symbol.Columns]);
    const extraValues = Array.isArray(extraConfig) ? extraConfig.flat(1) : Object.values(extraConfig);
    for (const builder of Object.values(extraValues)) {
      if (is(builder, IndexBuilder2)) {
        indexes.push(builder.build(table6));
      } else if (is(builder, CheckBuilder2)) {
        checks.push(builder.build(table6));
      } else if (is(builder, UniqueConstraintBuilder2)) {
        uniqueConstraints.push(builder.build(table6));
      } else if (is(builder, PrimaryKeyBuilder2)) {
        primaryKeys.push(builder.build(table6));
      } else if (is(builder, ForeignKeyBuilder2)) {
        foreignKeys.push(builder.build(table6));
      }
    }
  }
  return {
    columns,
    indexes,
    foreignKeys,
    checks,
    primaryKeys,
    uniqueConstraints,
    name: name2
  };
}
function extractUsedTable2(table6) {
  if (is(table6, SQLiteTable)) {
    return [`${table6[Table2.Symbol.BaseName]}`];
  }
  if (is(table6, Subquery)) {
    return table6._.usedTables ?? [];
  }
  if (is(table6, SQL)) {
    return table6.usedTables ?? [];
  }
  return [];
}
function getViewConfig2(view5) {
  return {
    ...view5[ViewBaseConfig]
    // ...view[SQLiteViewConfig],
  };
}
var init_utils7 = __esm({
  "../drizzle-orm/dist/sqlite-core/utils.js"() {
    "use strict";
    init_entity();
    init_sql();
    init_subquery();
    init_table();
    init_view_common();
    init_checks2();
    init_foreign_keys2();
    init_indexes2();
    init_primary_keys2();
    init_table3();
    init_unique_constraint2();
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/delete.js
var _a213, _b152, SQLiteDeleteBase;
var init_delete2 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/delete.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_selection_proxy();
    init_table3();
    init_table();
    init_utils2();
    init_utils7();
    SQLiteDeleteBase = class extends (_b152 = QueryPromise, _a213 = entityKind, _b152) {
      constructor(table6, session, dialect6, withList) {
        super();
        /** @internal */
        __publicField(this, "config");
        __publicField(this, "run", (placeholderValues) => {
          return this._prepare().run(placeholderValues);
        });
        __publicField(this, "all", (placeholderValues) => {
          return this._prepare().all(placeholderValues);
        });
        __publicField(this, "get", (placeholderValues) => {
          return this._prepare().get(placeholderValues);
        });
        __publicField(this, "values", (placeholderValues) => {
          return this._prepare().values(placeholderValues);
        });
        this.table = table6;
        this.session = session;
        this.dialect = dialect6;
        this.config = { table: table6, withList };
      }
      /**
       * Adds a `where` clause to the query.
       *
       * Calling this method will delete only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/delete}
       *
       * @param where the `where` clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be deleted.
       *
       * ```ts
       * // Delete all cars with green color
       * db.delete(cars).where(eq(cars.color, 'green'));
       * // or
       * db.delete(cars).where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Delete all BMW cars with a green color
       * db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Delete all cars with the green or blue color
       * db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        this.config.where = where;
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.table[Table2.Symbol.Columns],
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          this.config.orderBy = orderByArray;
        } else {
          const orderByArray = columns;
          this.config.orderBy = orderByArray;
        }
        return this;
      }
      limit(limit) {
        this.config.limit = limit;
        return this;
      }
      returning(fields = this.table[SQLiteTable.Symbol.Columns]) {
        this.config.returning = orderSelectedFields(fields);
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildDeleteQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(isOneTimeQuery = true) {
        return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](
          this.dialect.sqlToQuery(this.getSQL()),
          this.config.returning,
          this.config.returning ? "all" : "run",
          true,
          void 0,
          {
            type: "delete",
            tables: extractUsedTable2(this.config.table)
          }
        );
      }
      prepare() {
        return this._prepare(false);
      }
      async execute(placeholderValues) {
        return this._prepare().execute(placeholderValues);
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(SQLiteDeleteBase, _a213, "SQLiteDelete");
  }
});

// ../drizzle-orm/dist/sqlite-core/view-base.js
var _a214, _b153, SQLiteViewBase;
var init_view_base2 = __esm({
  "../drizzle-orm/dist/sqlite-core/view-base.js"() {
    "use strict";
    init_entity();
    init_sql();
    SQLiteViewBase = class extends (_b153 = View3, _a214 = entityKind, _b153) {
    };
    __publicField(SQLiteViewBase, _a214, "SQLiteViewBase");
  }
});

// ../drizzle-orm/dist/sqlite-core/dialect.js
var _a215, SQLiteDialect, _a216, _b154, SQLiteSyncDialect, _a217, _b155, SQLiteAsyncDialect;
var init_dialect2 = __esm({
  "../drizzle-orm/dist/sqlite-core/dialect.js"() {
    "use strict";
    init_alias();
    init_casing();
    init_column();
    init_entity();
    init_errors2();
    init_relations();
    init_sql2();
    init_sql();
    init_columns2();
    init_table3();
    init_subquery();
    init_table();
    init_utils2();
    init_view_common();
    init_view_base2();
    _a215 = entityKind;
    SQLiteDialect = class {
      constructor(config) {
        /** @internal */
        __publicField(this, "casing");
        this.casing = new CasingCache(config?.casing);
      }
      escapeName(name2) {
        return `"${name2}"`;
      }
      escapeParam(_num) {
        return "?";
      }
      escapeString(str) {
        return `'${str.replace(/'/g, "''")}'`;
      }
      buildWithCTE(queries) {
        if (!queries?.length) return void 0;
        const withSqlChunks = [sql`with `];
        for (const [i, w] of queries.entries()) {
          withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
          if (i < queries.length - 1) {
            withSqlChunks.push(sql`, `);
          }
        }
        withSqlChunks.push(sql` `);
        return sql.join(withSqlChunks);
      }
      buildDeleteQuery({ table: table6, where, returning, withList, limit, orderBy }) {
        const withSql = this.buildWithCTE(withList);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const whereSql = where ? sql` where ${where}` : void 0;
        const orderBySql = this.buildOrderBy(orderBy);
        const limitSql = this.buildLimit(limit);
        return sql`${withSql}delete from ${table6}${whereSql}${returningSql}${orderBySql}${limitSql}`;
      }
      buildUpdateSet(table6, set) {
        const tableColumns = table6[Table2.Symbol.Columns];
        const columnNames = Object.keys(tableColumns).filter(
          (colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0
        );
        const setSize = columnNames.length;
        return sql.join(columnNames.flatMap((colName, i) => {
          const col = tableColumns[colName];
          const value = set[colName] ?? sql.param(col.onUpdateFn(), col);
          const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
          if (i < setSize - 1) {
            return [res, sql.raw(", ")];
          }
          return [res];
        }));
      }
      buildUpdateQuery({ table: table6, set, where, returning, withList, joins, from, limit, orderBy }) {
        const withSql = this.buildWithCTE(withList);
        const setSql = this.buildUpdateSet(table6, set);
        const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]);
        const joinsSql = this.buildJoins(joins);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const whereSql = where ? sql` where ${where}` : void 0;
        const orderBySql = this.buildOrderBy(orderBy);
        const limitSql = this.buildLimit(limit);
        return sql`${withSql}update ${table6} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}${orderBySql}${limitSql}`;
      }
      /**
       * Builds selection SQL with provided fields/expressions
       *
       * Examples:
       *
       * `select <selection> from`
       *
       * `insert ... returning <selection>`
       *
       * If `isSingleTable` is true, then columns won't be prefixed with table name
       */
      buildSelection(fields, { isSingleTable = false } = {}) {
        const columnsLen = fields.length;
        const chunks = fields.flatMap(({ field }, i) => {
          const chunk = [];
          if (is(field, SQL.Aliased) && field.isSelectionField) {
            chunk.push(sql.identifier(field.fieldAlias));
          } else if (is(field, SQL.Aliased) || is(field, SQL)) {
            const query = is(field, SQL.Aliased) ? field.sql : field;
            if (isSingleTable) {
              chunk.push(
                new SQL(
                  query.queryChunks.map((c) => {
                    if (is(c, Column2)) {
                      return sql.identifier(this.casing.getColumnCasing(c));
                    }
                    return c;
                  })
                )
              );
            } else {
              chunk.push(query);
            }
            if (is(field, SQL.Aliased)) {
              chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
            }
          } else if (is(field, Column2)) {
            const tableName = field.table[Table2.Symbol.Name];
            if (field.columnType === "SQLiteNumericBigInt") {
              if (isSingleTable) {
                chunk.push(sql`cast(${sql.identifier(this.casing.getColumnCasing(field))} as text)`);
              } else {
                chunk.push(
                  sql`cast(${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))} as text)`
                );
              }
            } else {
              if (isSingleTable) {
                chunk.push(sql.identifier(this.casing.getColumnCasing(field)));
              } else {
                chunk.push(sql`${sql.identifier(tableName)}.${sql.identifier(this.casing.getColumnCasing(field))}`);
              }
            }
          }
          if (i < columnsLen - 1) {
            chunk.push(sql`, `);
          }
          return chunk;
        });
        return sql.join(chunks);
      }
      buildJoins(joins) {
        if (!joins || joins.length === 0) {
          return void 0;
        }
        const joinsArray = [];
        if (joins) {
          for (const [index6, joinMeta] of joins.entries()) {
            if (index6 === 0) {
              joinsArray.push(sql` `);
            }
            const table6 = joinMeta.table;
            const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0;
            if (is(table6, SQLiteTable)) {
              const tableName = table6[SQLiteTable.Symbol.Name];
              const tableSchema = table6[SQLiteTable.Symbol.Schema];
              const origTableName = table6[SQLiteTable.Symbol.OriginalName];
              const alias = tableName === origTableName ? void 0 : joinMeta.alias;
              joinsArray.push(
                sql`${sql.raw(joinMeta.joinType)} join ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`
              );
            } else {
              joinsArray.push(
                sql`${sql.raw(joinMeta.joinType)} join ${table6}${onSql}`
              );
            }
            if (index6 < joins.length - 1) {
              joinsArray.push(sql` `);
            }
          }
        }
        return sql.join(joinsArray);
      }
      buildLimit(limit) {
        return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
      }
      buildOrderBy(orderBy) {
        const orderByList = [];
        if (orderBy) {
          for (const [index6, orderByValue] of orderBy.entries()) {
            orderByList.push(orderByValue);
            if (index6 < orderBy.length - 1) {
              orderByList.push(sql`, `);
            }
          }
        }
        return orderByList.length > 0 ? sql` order by ${sql.join(orderByList)}` : void 0;
      }
      buildFromTable(table6) {
        if (is(table6, Table2) && table6[Table2.Symbol.IsAlias]) {
          return sql`${sql`${sql.identifier(table6[Table2.Symbol.Schema] ?? "")}.`.if(table6[Table2.Symbol.Schema])}${sql.identifier(table6[Table2.Symbol.OriginalName])} ${sql.identifier(table6[Table2.Symbol.Name])}`;
        }
        return table6;
      }
      buildSelectQuery({
        withList,
        fields,
        fieldsFlat,
        where,
        having,
        table: table6,
        joins,
        orderBy,
        groupBy,
        limit,
        offset,
        distinct,
        setOperators
      }) {
        const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
        for (const f of fieldsList) {
          if (is(f.field, Column2) && getTableName(f.field.table) !== (is(table6, Subquery) ? table6._.alias : is(table6, SQLiteViewBase) ? table6[ViewBaseConfig].name : is(table6, SQL) ? void 0 : getTableName(table6)) && !((table22) => joins?.some(
            ({ alias }) => alias === (table22[Table2.Symbol.IsAlias] ? getTableName(table22) : table22[Table2.Symbol.BaseName])
          ))(f.field.table)) {
            const tableName = getTableName(f.field.table);
            throw new Error(
              `Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`
            );
          }
        }
        const isSingleTable = !joins || joins.length === 0;
        const withSql = this.buildWithCTE(withList);
        const distinctSql = distinct ? sql` distinct` : void 0;
        const selection = this.buildSelection(fieldsList, { isSingleTable });
        const tableSql = this.buildFromTable(table6);
        const joinsSql = this.buildJoins(joins);
        const whereSql = where ? sql` where ${where}` : void 0;
        const havingSql = having ? sql` having ${having}` : void 0;
        const groupByList = [];
        if (groupBy) {
          for (const [index6, groupByValue] of groupBy.entries()) {
            groupByList.push(groupByValue);
            if (index6 < groupBy.length - 1) {
              groupByList.push(sql`, `);
            }
          }
        }
        const groupBySql = groupByList.length > 0 ? sql` group by ${sql.join(groupByList)}` : void 0;
        const orderBySql = this.buildOrderBy(orderBy);
        const limitSql = this.buildLimit(limit);
        const offsetSql = offset ? sql` offset ${offset}` : void 0;
        const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}`;
        if (setOperators.length > 0) {
          return this.buildSetOperations(finalQuery, setOperators);
        }
        return finalQuery;
      }
      buildSetOperations(leftSelect, setOperators) {
        const [setOperator, ...rest] = setOperators;
        if (!setOperator) {
          throw new Error("Cannot pass undefined values to any set operator");
        }
        if (rest.length === 0) {
          return this.buildSetOperationQuery({ leftSelect, setOperator });
        }
        return this.buildSetOperations(
          this.buildSetOperationQuery({ leftSelect, setOperator }),
          rest
        );
      }
      buildSetOperationQuery({
        leftSelect,
        setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
      }) {
        const leftChunk = sql`${leftSelect.getSQL()} `;
        const rightChunk = sql`${rightSelect.getSQL()}`;
        let orderBySql;
        if (orderBy && orderBy.length > 0) {
          const orderByValues = [];
          for (const singleOrderBy of orderBy) {
            if (is(singleOrderBy, SQLiteColumn)) {
              orderByValues.push(sql.identifier(singleOrderBy.name));
            } else if (is(singleOrderBy, SQL)) {
              for (let i = 0; i < singleOrderBy.queryChunks.length; i++) {
                const chunk = singleOrderBy.queryChunks[i];
                if (is(chunk, SQLiteColumn)) {
                  singleOrderBy.queryChunks[i] = sql.identifier(this.casing.getColumnCasing(chunk));
                }
              }
              orderByValues.push(sql`${singleOrderBy}`);
            } else {
              orderByValues.push(sql`${singleOrderBy}`);
            }
          }
          orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)}`;
        }
        const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
        const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
        const offsetSql = offset ? sql` offset ${offset}` : void 0;
        return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
      }
      buildInsertQuery({ table: table6, values: valuesOrSelect, onConflict, returning, withList, select }) {
        const valuesSqlList = [];
        const columns = table6[Table2.Symbol.Columns];
        const colEntries = Object.entries(columns).filter(
          ([_2, col]) => !col.shouldDisableInsert()
        );
        const insertOrder = colEntries.map(([, column6]) => sql.identifier(this.casing.getColumnCasing(column6)));
        if (select) {
          const select2 = valuesOrSelect;
          if (is(select2, SQL)) {
            valuesSqlList.push(select2);
          } else {
            valuesSqlList.push(select2.getSQL());
          }
        } else {
          const values = valuesOrSelect;
          valuesSqlList.push(sql.raw("values "));
          for (const [valueIndex, value] of values.entries()) {
            const valueList = [];
            for (const [fieldName, col] of colEntries) {
              const colValue = value[fieldName];
              if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
                let defaultValue;
                if (col.default !== null && col.default !== void 0) {
                  defaultValue = is(col.default, SQL) ? col.default : sql.param(col.default, col);
                } else if (col.defaultFn !== void 0) {
                  const defaultFnResult = col.defaultFn();
                  defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
                } else if (!col.default && col.onUpdateFn !== void 0) {
                  const onUpdateFnResult = col.onUpdateFn();
                  defaultValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
                } else {
                  defaultValue = sql`null`;
                }
                valueList.push(defaultValue);
              } else {
                valueList.push(colValue);
              }
            }
            valuesSqlList.push(valueList);
            if (valueIndex < values.length - 1) {
              valuesSqlList.push(sql`, `);
            }
          }
        }
        const withSql = this.buildWithCTE(withList);
        const valuesSql = sql.join(valuesSqlList);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const onConflictSql = onConflict?.length ? sql.join(onConflict) : void 0;
        return sql`${withSql}insert into ${table6} ${insertOrder} ${valuesSql}${onConflictSql}${returningSql}`;
      }
      sqlToQuery(sql2, invokeSource) {
        return sql2.toQuery({
          casing: this.casing,
          escapeName: this.escapeName,
          escapeParam: this.escapeParam,
          escapeString: this.escapeString,
          invokeSource
        });
      }
      buildRelationalQuery({
        fullSchema,
        schema: schema5,
        tableNamesMap,
        table: table6,
        tableConfig,
        queryConfig: config,
        tableAlias,
        nestedQueryRelation,
        joinOn
      }) {
        let selection = [];
        let limit, offset, orderBy = [], where;
        const joins = [];
        if (config === true) {
          const selectionEntries = Object.entries(tableConfig.columns);
          selection = selectionEntries.map(([key, value]) => ({
            dbKey: value.name,
            tsKey: key,
            field: aliasedTableColumn(value, tableAlias),
            relationTableTsKey: void 0,
            isJson: false,
            selection: []
          }));
        } else {
          const aliasedColumns = Object.fromEntries(
            Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)])
          );
          if (config.where) {
            const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
            where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
          }
          const fieldsSelection = [];
          let selectedColumns = [];
          if (config.columns) {
            let isIncludeMode = false;
            for (const [field, value] of Object.entries(config.columns)) {
              if (value === void 0) {
                continue;
              }
              if (field in tableConfig.columns) {
                if (!isIncludeMode && value === true) {
                  isIncludeMode = true;
                }
                selectedColumns.push(field);
              }
            }
            if (selectedColumns.length > 0) {
              selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
            }
          } else {
            selectedColumns = Object.keys(tableConfig.columns);
          }
          for (const field of selectedColumns) {
            const column6 = tableConfig.columns[field];
            fieldsSelection.push({ tsKey: field, value: column6 });
          }
          let selectedRelations = [];
          if (config.with) {
            selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
          }
          let extras;
          if (config.extras) {
            extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
            for (const [tsKey, value] of Object.entries(extras)) {
              fieldsSelection.push({
                tsKey,
                value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
              });
            }
          }
          for (const { tsKey, value } of fieldsSelection) {
            selection.push({
              dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
              tsKey,
              field: is(value, Column2) ? aliasedTableColumn(value, tableAlias) : value,
              relationTableTsKey: void 0,
              isJson: false,
              selection: []
            });
          }
          let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
          if (!Array.isArray(orderByOrig)) {
            orderByOrig = [orderByOrig];
          }
          orderBy = orderByOrig.map((orderByValue) => {
            if (is(orderByValue, Column2)) {
              return aliasedTableColumn(orderByValue, tableAlias);
            }
            return mapColumnsInSQLToAlias(orderByValue, tableAlias);
          });
          limit = config.limit;
          offset = config.offset;
          for (const {
            tsKey: selectedRelationTsKey,
            queryConfig: selectedRelationConfigValue,
            relation
          } of selectedRelations) {
            const normalizedRelation = normalizeRelation(schema5, tableNamesMap, relation);
            const relationTableName = getTableUniqueName(relation.referencedTable);
            const relationTableTsName = tableNamesMap[relationTableName];
            const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
            const joinOn2 = and(
              ...normalizedRelation.fields.map(
                (field2, i) => eq(
                  aliasedTableColumn(normalizedRelation.references[i], relationTableAlias),
                  aliasedTableColumn(field2, tableAlias)
                )
              )
            );
            const builtRelation = this.buildRelationalQuery({
              fullSchema,
              schema: schema5,
              tableNamesMap,
              table: fullSchema[relationTableTsName],
              tableConfig: schema5[relationTableTsName],
              queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
              tableAlias: relationTableAlias,
              joinOn: joinOn2,
              nestedQueryRelation: relation
            });
            const field = sql`(${builtRelation.sql})`.as(selectedRelationTsKey);
            selection.push({
              dbKey: selectedRelationTsKey,
              tsKey: selectedRelationTsKey,
              field,
              relationTableTsKey: relationTableTsName,
              isJson: true,
              selection: builtRelation.selection
            });
          }
        }
        if (selection.length === 0) {
          throw new DrizzleError({
            message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`
          });
        }
        let result;
        where = and(joinOn, where);
        if (nestedQueryRelation) {
          let field = sql`json_array(${sql.join(
            selection.map(
              ({ field: field2 }) => is(field2, SQLiteColumn) ? sql.identifier(this.casing.getColumnCasing(field2)) : is(field2, SQL.Aliased) ? field2.sql : field2
            ),
            sql`, `
          )})`;
          if (is(nestedQueryRelation, Many)) {
            field = sql`coalesce(json_group_array(${field}), json_array())`;
          }
          const nestedSelection = [{
            dbKey: "data",
            tsKey: "data",
            field: field.as("data"),
            isJson: true,
            relationTableTsKey: tableConfig.tsName,
            selection
          }];
          const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0;
          if (needsSubquery) {
            result = this.buildSelectQuery({
              table: aliasedTable(table6, tableAlias),
              fields: {},
              fieldsFlat: [
                {
                  path: [],
                  field: sql.raw("*")
                }
              ],
              where,
              limit,
              offset,
              orderBy,
              setOperators: []
            });
            where = void 0;
            limit = void 0;
            offset = void 0;
            orderBy = void 0;
          } else {
            result = aliasedTable(table6, tableAlias);
          }
          result = this.buildSelectQuery({
            table: is(result, SQLiteTable) ? result : new Subquery(result, {}, tableAlias),
            fields: {},
            fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
              path: [],
              field: is(field2, Column2) ? aliasedTableColumn(field2, tableAlias) : field2
            })),
            joins,
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        } else {
          result = this.buildSelectQuery({
            table: aliasedTable(table6, tableAlias),
            fields: {},
            fieldsFlat: selection.map(({ field }) => ({
              path: [],
              field: is(field, Column2) ? aliasedTableColumn(field, tableAlias) : field
            })),
            joins,
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        }
        return {
          tableTsKey: tableConfig.tsName,
          sql: result,
          selection
        };
      }
    };
    __publicField(SQLiteDialect, _a215, "SQLiteDialect");
    SQLiteSyncDialect = class extends (_b154 = SQLiteDialect, _a216 = entityKind, _b154) {
      migrate(migrations, session, config) {
        const migrationsTable = config === void 0 ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
        const migrationTableCreate = sql`
			CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (
				id SERIAL PRIMARY KEY,
				hash text NOT NULL,
				created_at numeric
			)
		`;
        session.run(migrationTableCreate);
        const dbMigrations = session.values(
          sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`
        );
        const lastDbMigration = dbMigrations[0] ?? void 0;
        session.run(sql`BEGIN`);
        try {
          for (const migration of migrations) {
            if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
              for (const stmt of migration.sql) {
                session.run(sql.raw(stmt));
              }
              session.run(
                sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`
              );
            }
          }
          session.run(sql`COMMIT`);
        } catch (e) {
          session.run(sql`ROLLBACK`);
          throw e;
        }
      }
    };
    __publicField(SQLiteSyncDialect, _a216, "SQLiteSyncDialect");
    SQLiteAsyncDialect = class extends (_b155 = SQLiteDialect, _a217 = entityKind, _b155) {
      async migrate(migrations, session, config) {
        const migrationsTable = config === void 0 ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
        const migrationTableCreate = sql`
			CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsTable)} (
				id SERIAL PRIMARY KEY,
				hash text NOT NULL,
				created_at numeric
			)
		`;
        await session.run(migrationTableCreate);
        const dbMigrations = await session.values(
          sql`SELECT id, hash, created_at FROM ${sql.identifier(migrationsTable)} ORDER BY created_at DESC LIMIT 1`
        );
        const lastDbMigration = dbMigrations[0] ?? void 0;
        await session.transaction(async (tx) => {
          for (const migration of migrations) {
            if (!lastDbMigration || Number(lastDbMigration[2]) < migration.folderMillis) {
              for (const stmt of migration.sql) {
                await tx.run(sql.raw(stmt));
              }
              await tx.run(
                sql`INSERT INTO ${sql.identifier(migrationsTable)} ("hash", "created_at") VALUES(${migration.hash}, ${migration.folderMillis})`
              );
            }
          }
        });
      }
    };
    __publicField(SQLiteAsyncDialect, _a217, "SQLiteAsyncDialect");
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/select.js
function createSetOperator2(type, isAll) {
  return (leftSelect, rightSelect, ...restSelects) => {
    const setOperators = [rightSelect, ...restSelects].map((select) => ({
      type,
      isAll,
      rightSelect: select
    }));
    for (const setOperator of setOperators) {
      if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
        throw new Error(
          "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
        );
      }
    }
    return leftSelect.addSetOperators(setOperators);
  };
}
var _a218, SQLiteSelectBuilder, _a219, _b156, SQLiteSelectQueryBuilderBase, _a220, _b157, SQLiteSelectBase, getSQLiteSetOperators, union3, unionAll2, intersect2, except2;
var init_select3 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/select.js"() {
    "use strict";
    init_entity();
    init_query_builder();
    init_query_promise();
    init_selection_proxy();
    init_sql();
    init_subquery();
    init_table();
    init_utils2();
    init_view_common();
    init_utils7();
    init_view_base2();
    _a218 = entityKind;
    SQLiteSelectBuilder = class {
      constructor(config) {
        __publicField(this, "fields");
        __publicField(this, "session");
        __publicField(this, "dialect");
        __publicField(this, "withList");
        __publicField(this, "distinct");
        this.fields = config.fields;
        this.session = config.session;
        this.dialect = config.dialect;
        this.withList = config.withList;
        this.distinct = config.distinct;
      }
      from(source) {
        const isPartialSelect = !!this.fields;
        let fields;
        if (this.fields) {
          fields = this.fields;
        } else if (is(source, Subquery)) {
          fields = Object.fromEntries(
            Object.keys(source._.selectedFields).map((key) => [key, source[key]])
          );
        } else if (is(source, SQLiteViewBase)) {
          fields = source[ViewBaseConfig].selectedFields;
        } else if (is(source, SQL)) {
          fields = {};
        } else {
          fields = getTableColumns(source);
        }
        return new SQLiteSelectBase({
          table: source,
          fields,
          isPartialSelect,
          session: this.session,
          dialect: this.dialect,
          withList: this.withList,
          distinct: this.distinct
        });
      }
    };
    __publicField(SQLiteSelectBuilder, _a218, "SQLiteSelectBuilder");
    SQLiteSelectQueryBuilderBase = class extends (_b156 = TypedQueryBuilder, _a219 = entityKind, _b156) {
      constructor({ table: table6, fields, isPartialSelect, session, dialect: dialect6, withList, distinct }) {
        super();
        __publicField(this, "_");
        /** @internal */
        __publicField(this, "config");
        __publicField(this, "joinsNotNullableMap");
        __publicField(this, "tableName");
        __publicField(this, "isPartialSelect");
        __publicField(this, "session");
        __publicField(this, "dialect");
        __publicField(this, "cacheConfig");
        __publicField(this, "usedTables", /* @__PURE__ */ new Set());
        /**
         * Executes a `left join` operation by adding another table to the current query.
         *
         * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select()
         *   .from(users)
         *   .leftJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .leftJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "leftJoin", this.createJoin("left"));
        /**
         * Executes a `right join` operation by adding another table to the current query.
         *
         * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select()
         *   .from(users)
         *   .rightJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .rightJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "rightJoin", this.createJoin("right"));
        /**
         * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
         *
         * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
         *   .from(users)
         *   .innerJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .innerJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "innerJoin", this.createJoin("inner"));
        /**
         * Executes a `full join` operation by combining rows from two tables into a new table.
         *
         * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User | null; pets: Pet | null; }[] = await db.select()
         *   .from(users)
         *   .fullJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number | null; petId: number | null; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .fullJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "fullJoin", this.createJoin("full"));
        /**
         * Executes a `cross join` operation by combining rows from two tables into a new table.
         *
         * Calling this method retrieves all rows from both main and joined tables, merging all rows from each table.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
         *
         * @param table the table to join.
         *
         * @example
         *
         * ```ts
         * // Select all users, each user with every pet
         * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
         *   .from(users)
         *   .crossJoin(pets)
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .crossJoin(pets)
         * ```
         */
        __publicField(this, "crossJoin", this.createJoin("cross"));
        /**
         * Adds `union` set operator to the query.
         *
         * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
         *
         * @example
         *
         * ```ts
         * // Select all unique names from customers and users tables
         * await db.select({ name: users.name })
         *   .from(users)
         *   .union(
         *     db.select({ name: customers.name }).from(customers)
         *   );
         * // or
         * import { union } from 'drizzle-orm/sqlite-core'
         *
         * await union(
         *   db.select({ name: users.name }).from(users),
         *   db.select({ name: customers.name }).from(customers)
         * );
         * ```
         */
        __publicField(this, "union", this.createSetOperator("union", false));
        /**
         * Adds `union all` set operator to the query.
         *
         * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
         *
         * @example
         *
         * ```ts
         * // Select all transaction ids from both online and in-store sales
         * await db.select({ transaction: onlineSales.transactionId })
         *   .from(onlineSales)
         *   .unionAll(
         *     db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
         *   );
         * // or
         * import { unionAll } from 'drizzle-orm/sqlite-core'
         *
         * await unionAll(
         *   db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
         *   db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
         * );
         * ```
         */
        __publicField(this, "unionAll", this.createSetOperator("union", true));
        /**
         * Adds `intersect` set operator to the query.
         *
         * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
         *
         * @example
         *
         * ```ts
         * // Select course names that are offered in both departments A and B
         * await db.select({ courseName: depA.courseName })
         *   .from(depA)
         *   .intersect(
         *     db.select({ courseName: depB.courseName }).from(depB)
         *   );
         * // or
         * import { intersect } from 'drizzle-orm/sqlite-core'
         *
         * await intersect(
         *   db.select({ courseName: depA.courseName }).from(depA),
         *   db.select({ courseName: depB.courseName }).from(depB)
         * );
         * ```
         */
        __publicField(this, "intersect", this.createSetOperator("intersect", false));
        /**
         * Adds `except` set operator to the query.
         *
         * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
         *
         * @example
         *
         * ```ts
         * // Select all courses offered in department A but not in department B
         * await db.select({ courseName: depA.courseName })
         *   .from(depA)
         *   .except(
         *     db.select({ courseName: depB.courseName }).from(depB)
         *   );
         * // or
         * import { except } from 'drizzle-orm/sqlite-core'
         *
         * await except(
         *   db.select({ courseName: depA.courseName }).from(depA),
         *   db.select({ courseName: depB.courseName }).from(depB)
         * );
         * ```
         */
        __publicField(this, "except", this.createSetOperator("except", false));
        this.config = {
          withList,
          table: table6,
          fields: { ...fields },
          distinct,
          setOperators: []
        };
        this.isPartialSelect = isPartialSelect;
        this.session = session;
        this.dialect = dialect6;
        this._ = {
          selectedFields: fields,
          config: this.config
        };
        this.tableName = getTableLikeName(table6);
        this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
        for (const item of extractUsedTable2(table6)) this.usedTables.add(item);
      }
      /** @internal */
      getUsedTables() {
        return [...this.usedTables];
      }
      createJoin(joinType) {
        return (table6, on) => {
          const baseTableName = this.tableName;
          const tableName = getTableLikeName(table6);
          for (const item of extractUsedTable2(table6)) this.usedTables.add(item);
          if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
            throw new Error(`Alias "${tableName}" is already used in this query`);
          }
          if (!this.isPartialSelect) {
            if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
              this.config.fields = {
                [baseTableName]: this.config.fields
              };
            }
            if (typeof tableName === "string" && !is(table6, SQL)) {
              const selection = is(table6, Subquery) ? table6._.selectedFields : is(table6, View3) ? table6[ViewBaseConfig].selectedFields : table6[Table2.Symbol.Columns];
              this.config.fields[tableName] = selection;
            }
          }
          if (typeof on === "function") {
            on = on(
              new Proxy(
                this.config.fields,
                new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
              )
            );
          }
          if (!this.config.joins) {
            this.config.joins = [];
          }
          this.config.joins.push({ on, table: table6, joinType, alias: tableName });
          if (typeof tableName === "string") {
            switch (joinType) {
              case "left": {
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
              case "right": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "cross":
              case "inner": {
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "full": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
            }
          }
          return this;
        };
      }
      createSetOperator(type, isAll) {
        return (rightSelection) => {
          const rightSelect = typeof rightSelection === "function" ? rightSelection(getSQLiteSetOperators()) : rightSelection;
          if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {
            throw new Error(
              "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
            );
          }
          this.config.setOperators.push({ type, isAll, rightSelect });
          return this;
        };
      }
      /** @internal */
      addSetOperators(setOperators) {
        this.config.setOperators.push(...setOperators);
        return this;
      }
      /**
       * Adds a `where` clause to the query.
       *
       * Calling this method will select only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#filtering}
       *
       * @param where the `where` clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be selected.
       *
       * ```ts
       * // Select all cars with green color
       * await db.select().from(cars).where(eq(cars.color, 'green'));
       * // or
       * await db.select().from(cars).where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Select all BMW cars with a green color
       * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Select all cars with the green or blue color
       * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        if (typeof where === "function") {
          where = where(
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
            )
          );
        }
        this.config.where = where;
        return this;
      }
      /**
       * Adds a `having` clause to the query.
       *
       * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
       *
       * @param having the `having` clause.
       *
       * @example
       *
       * ```ts
       * // Select all brands with more than one car
       * await db.select({
       * 	brand: cars.brand,
       * 	count: sql<number>`cast(count(${cars.id}) as int)`,
       * })
       *   .from(cars)
       *   .groupBy(cars.brand)
       *   .having(({ count }) => gt(count, 1));
       * ```
       */
      having(having) {
        if (typeof having === "function") {
          having = having(
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
            )
          );
        }
        this.config.having = having;
        return this;
      }
      groupBy(...columns) {
        if (typeof columns[0] === "function") {
          const groupBy = columns[0](
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
        } else {
          this.config.groupBy = columns;
        }
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          if (this.config.setOperators.length > 0) {
            this.config.setOperators.at(-1).orderBy = orderByArray;
          } else {
            this.config.orderBy = orderByArray;
          }
        } else {
          const orderByArray = columns;
          if (this.config.setOperators.length > 0) {
            this.config.setOperators.at(-1).orderBy = orderByArray;
          } else {
            this.config.orderBy = orderByArray;
          }
        }
        return this;
      }
      /**
       * Adds a `limit` clause to the query.
       *
       * Calling this method will set the maximum number of rows that will be returned by this query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
       *
       * @param limit the `limit` clause.
       *
       * @example
       *
       * ```ts
       * // Get the first 10 people from this query.
       * await db.select().from(people).limit(10);
       * ```
       */
      limit(limit) {
        if (this.config.setOperators.length > 0) {
          this.config.setOperators.at(-1).limit = limit;
        } else {
          this.config.limit = limit;
        }
        return this;
      }
      /**
       * Adds an `offset` clause to the query.
       *
       * Calling this method will skip a number of rows when returning results from this query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
       *
       * @param offset the `offset` clause.
       *
       * @example
       *
       * ```ts
       * // Get the 10th-20th people from this query.
       * await db.select().from(people).offset(10).limit(10);
       * ```
       */
      offset(offset) {
        if (this.config.setOperators.length > 0) {
          this.config.setOperators.at(-1).offset = offset;
        } else {
          this.config.offset = offset;
        }
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildSelectQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      as(alias) {
        const usedTables = [];
        usedTables.push(...extractUsedTable2(this.config.table));
        if (this.config.joins) {
          for (const it of this.config.joins) usedTables.push(...extractUsedTable2(it.table));
        }
        return new Proxy(
          new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]),
          new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
        );
      }
      /** @internal */
      getSelectedFields() {
        return new Proxy(
          this.config.fields,
          new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
        );
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(SQLiteSelectQueryBuilderBase, _a219, "SQLiteSelectQueryBuilder");
    SQLiteSelectBase = class extends (_b157 = SQLiteSelectQueryBuilderBase, _a220 = entityKind, _b157) {
      constructor() {
        super(...arguments);
        __publicField(this, "run", (placeholderValues) => {
          return this._prepare().run(placeholderValues);
        });
        __publicField(this, "all", (placeholderValues) => {
          return this._prepare().all(placeholderValues);
        });
        __publicField(this, "get", (placeholderValues) => {
          return this._prepare().get(placeholderValues);
        });
        __publicField(this, "values", (placeholderValues) => {
          return this._prepare().values(placeholderValues);
        });
      }
      /** @internal */
      _prepare(isOneTimeQuery = true) {
        if (!this.session) {
          throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
        }
        const fieldsList = orderSelectedFields(this.config.fields);
        const query = this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](
          this.dialect.sqlToQuery(this.getSQL()),
          fieldsList,
          "all",
          true,
          void 0,
          {
            type: "select",
            tables: [...this.usedTables]
          },
          this.cacheConfig
        );
        query.joinsNotNullableMap = this.joinsNotNullableMap;
        return query;
      }
      $withCache(config) {
        this.cacheConfig = config === void 0 ? { config: {}, enable: true, autoInvalidate: true } : config === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config };
        return this;
      }
      prepare() {
        return this._prepare(false);
      }
      async execute() {
        return this.all();
      }
    };
    __publicField(SQLiteSelectBase, _a220, "SQLiteSelect");
    applyMixins(SQLiteSelectBase, [QueryPromise]);
    getSQLiteSetOperators = () => ({
      union: union3,
      unionAll: unionAll2,
      intersect: intersect2,
      except: except2
    });
    union3 = createSetOperator2("union", false);
    unionAll2 = createSetOperator2("union", true);
    intersect2 = createSetOperator2("intersect", false);
    except2 = createSetOperator2("except", false);
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/query-builder.js
var _a221, QueryBuilder2;
var init_query_builder3 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/query-builder.js"() {
    "use strict";
    init_entity();
    init_selection_proxy();
    init_dialect2();
    init_subquery();
    init_select3();
    _a221 = entityKind;
    QueryBuilder2 = class {
      constructor(dialect6) {
        __publicField(this, "dialect");
        __publicField(this, "dialectConfig");
        __publicField(this, "$with", (alias, selection) => {
          const queryBuilder = this;
          const as = (qb) => {
            if (typeof qb === "function") {
              qb = qb(queryBuilder);
            }
            return new Proxy(
              new WithSubquery(
                qb.getSQL(),
                selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
                alias,
                true
              ),
              new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
            );
          };
          return { as };
        });
        this.dialect = is(dialect6, SQLiteDialect) ? dialect6 : void 0;
        this.dialectConfig = is(dialect6, SQLiteDialect) ? void 0 : dialect6;
      }
      with(...queries) {
        const self2 = this;
        function select(fields) {
          return new SQLiteSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self2.getDialect(),
            withList: queries
          });
        }
        function selectDistinct(fields) {
          return new SQLiteSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self2.getDialect(),
            withList: queries,
            distinct: true
          });
        }
        return { select, selectDistinct };
      }
      select(fields) {
        return new SQLiteSelectBuilder({ fields: fields ?? void 0, session: void 0, dialect: this.getDialect() });
      }
      selectDistinct(fields) {
        return new SQLiteSelectBuilder({
          fields: fields ?? void 0,
          session: void 0,
          dialect: this.getDialect(),
          distinct: true
        });
      }
      // Lazy load dialect to avoid circular dependency
      getDialect() {
        if (!this.dialect) {
          this.dialect = new SQLiteSyncDialect(this.dialectConfig);
        }
        return this.dialect;
      }
    };
    __publicField(QueryBuilder2, _a221, "SQLiteQueryBuilder");
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/insert.js
var _a222, SQLiteInsertBuilder, _a223, _b158, SQLiteInsertBase;
var init_insert2 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/insert.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_sql();
    init_table3();
    init_table();
    init_utils2();
    init_utils7();
    init_query_builder3();
    _a222 = entityKind;
    SQLiteInsertBuilder = class {
      constructor(table6, session, dialect6, withList) {
        this.table = table6;
        this.session = session;
        this.dialect = dialect6;
        this.withList = withList;
      }
      values(values) {
        values = Array.isArray(values) ? values : [values];
        if (values.length === 0) {
          throw new Error("values() must be called with at least one value");
        }
        const mappedValues = values.map((entry) => {
          const result = {};
          const cols = this.table[Table2.Symbol.Columns];
          for (const colKey of Object.keys(entry)) {
            const colValue = entry[colKey];
            result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
          }
          return result;
        });
        return new SQLiteInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList);
      }
      select(selectQuery) {
        const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder2()) : selectQuery;
        if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) {
          throw new Error(
            "Insert select error: selected fields are not the same or are in a different order compared to the table definition"
          );
        }
        return new SQLiteInsertBase(this.table, select, this.session, this.dialect, this.withList, true);
      }
    };
    __publicField(SQLiteInsertBuilder, _a222, "SQLiteInsertBuilder");
    SQLiteInsertBase = class extends (_b158 = QueryPromise, _a223 = entityKind, _b158) {
      constructor(table6, values, session, dialect6, withList, select) {
        super();
        /** @internal */
        __publicField(this, "config");
        __publicField(this, "run", (placeholderValues) => {
          return this._prepare().run(placeholderValues);
        });
        __publicField(this, "all", (placeholderValues) => {
          return this._prepare().all(placeholderValues);
        });
        __publicField(this, "get", (placeholderValues) => {
          return this._prepare().get(placeholderValues);
        });
        __publicField(this, "values", (placeholderValues) => {
          return this._prepare().values(placeholderValues);
        });
        this.session = session;
        this.dialect = dialect6;
        this.config = { table: table6, values, withList, select };
      }
      returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
        this.config.returning = orderSelectedFields(fields);
        return this;
      }
      /**
       * Adds an `on conflict do nothing` clause to the query.
       *
       * Calling this method simply avoids inserting a row as its alternative action.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}
       *
       * @param config The `target` and `where` clauses.
       *
       * @example
       * ```ts
       * // Insert one row and cancel the insert if there's a conflict
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoNothing();
       *
       * // Explicitly specify conflict target
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoNothing({ target: cars.id });
       * ```
       */
      onConflictDoNothing(config = {}) {
        if (!this.config.onConflict) this.config.onConflict = [];
        if (config.target === void 0) {
          this.config.onConflict.push(sql` on conflict do nothing`);
        } else {
          const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
          const whereSql = config.where ? sql` where ${config.where}` : sql``;
          this.config.onConflict.push(sql` on conflict ${targetSql} do nothing${whereSql}`);
        }
        return this;
      }
      /**
       * Adds an `on conflict do update` clause to the query.
       *
       * Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}
       *
       * @param config The `target`, `set` and `where` clauses.
       *
       * @example
       * ```ts
       * // Update the row if there's a conflict
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoUpdate({
       *     target: cars.id,
       *     set: { brand: 'Porsche' }
       *   });
       *
       * // Upsert with 'where' clause
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onConflictDoUpdate({
       *     target: cars.id,
       *     set: { brand: 'newBMW' },
       *     where: sql`${cars.createdAt} > '2023-01-01'::date`,
       *   });
       * ```
       */
      onConflictDoUpdate(config) {
        if (config.where && (config.targetWhere || config.setWhere)) {
          throw new Error(
            'You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'
          );
        }
        if (!this.config.onConflict) this.config.onConflict = [];
        const whereSql = config.where ? sql` where ${config.where}` : void 0;
        const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;
        const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;
        const targetSql = Array.isArray(config.target) ? sql`${config.target}` : sql`${[config.target]}`;
        const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
        this.config.onConflict.push(
          sql` on conflict ${targetSql}${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`
        );
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildInsertQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(isOneTimeQuery = true) {
        return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](
          this.dialect.sqlToQuery(this.getSQL()),
          this.config.returning,
          this.config.returning ? "all" : "run",
          true,
          void 0,
          {
            type: "insert",
            tables: extractUsedTable2(this.config.table)
          }
        );
      }
      prepare() {
        return this._prepare(false);
      }
      async execute() {
        return this.config.returning ? this.all() : this.run();
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(SQLiteInsertBase, _a223, "SQLiteInsert");
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/select.types.js
var init_select_types2 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/select.types.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/update.js
var _a224, SQLiteUpdateBuilder, _a225, _b159, SQLiteUpdateBase;
var init_update2 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/update.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_selection_proxy();
    init_table3();
    init_subquery();
    init_table();
    init_utils2();
    init_view_common();
    init_utils7();
    init_view_base2();
    _a224 = entityKind;
    SQLiteUpdateBuilder = class {
      constructor(table6, session, dialect6, withList) {
        this.table = table6;
        this.session = session;
        this.dialect = dialect6;
        this.withList = withList;
      }
      set(values) {
        return new SQLiteUpdateBase(
          this.table,
          mapUpdateSet(this.table, values),
          this.session,
          this.dialect,
          this.withList
        );
      }
    };
    __publicField(SQLiteUpdateBuilder, _a224, "SQLiteUpdateBuilder");
    SQLiteUpdateBase = class extends (_b159 = QueryPromise, _a225 = entityKind, _b159) {
      constructor(table6, set, session, dialect6, withList) {
        super();
        /** @internal */
        __publicField(this, "config");
        __publicField(this, "leftJoin", this.createJoin("left"));
        __publicField(this, "rightJoin", this.createJoin("right"));
        __publicField(this, "innerJoin", this.createJoin("inner"));
        __publicField(this, "fullJoin", this.createJoin("full"));
        __publicField(this, "run", (placeholderValues) => {
          return this._prepare().run(placeholderValues);
        });
        __publicField(this, "all", (placeholderValues) => {
          return this._prepare().all(placeholderValues);
        });
        __publicField(this, "get", (placeholderValues) => {
          return this._prepare().get(placeholderValues);
        });
        __publicField(this, "values", (placeholderValues) => {
          return this._prepare().values(placeholderValues);
        });
        this.session = session;
        this.dialect = dialect6;
        this.config = { set, table: table6, withList, joins: [] };
      }
      from(source) {
        this.config.from = source;
        return this;
      }
      createJoin(joinType) {
        return (table6, on) => {
          const tableName = getTableLikeName(table6);
          if (typeof tableName === "string" && this.config.joins.some((join) => join.alias === tableName)) {
            throw new Error(`Alias "${tableName}" is already used in this query`);
          }
          if (typeof on === "function") {
            const from = this.config.from ? is(table6, SQLiteTable) ? table6[Table2.Symbol.Columns] : is(table6, Subquery) ? table6._.selectedFields : is(table6, SQLiteViewBase) ? table6[ViewBaseConfig].selectedFields : void 0 : void 0;
            on = on(
              new Proxy(
                this.config.table[Table2.Symbol.Columns],
                new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
              ),
              from && new Proxy(
                from,
                new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
              )
            );
          }
          this.config.joins.push({ on, table: table6, joinType, alias: tableName });
          return this;
        };
      }
      /**
       * Adds a 'where' clause to the query.
       *
       * Calling this method will update only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/update}
       *
       * @param where the 'where' clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be updated.
       *
       * ```ts
       * // Update all cars with green color
       * db.update(cars).set({ color: 'red' })
       *   .where(eq(cars.color, 'green'));
       * // or
       * db.update(cars).set({ color: 'red' })
       *   .where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Update all BMW cars with a green color
       * db.update(cars).set({ color: 'red' })
       *   .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Update all cars with the green or blue color
       * db.update(cars).set({ color: 'red' })
       *   .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        this.config.where = where;
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.table[Table2.Symbol.Columns],
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          this.config.orderBy = orderByArray;
        } else {
          const orderByArray = columns;
          this.config.orderBy = orderByArray;
        }
        return this;
      }
      limit(limit) {
        this.config.limit = limit;
        return this;
      }
      returning(fields = this.config.table[SQLiteTable.Symbol.Columns]) {
        this.config.returning = orderSelectedFields(fields);
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildUpdateQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      /** @internal */
      _prepare(isOneTimeQuery = true) {
        return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](
          this.dialect.sqlToQuery(this.getSQL()),
          this.config.returning,
          this.config.returning ? "all" : "run",
          true,
          void 0,
          {
            type: "insert",
            tables: extractUsedTable2(this.config.table)
          }
        );
      }
      prepare() {
        return this._prepare(false);
      }
      async execute() {
        return this.config.returning ? this.all() : this.run();
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(SQLiteUpdateBase, _a225, "SQLiteUpdate");
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/index.js
var init_query_builders2 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/index.js"() {
    "use strict";
    init_delete2();
    init_insert2();
    init_query_builder3();
    init_select3();
    init_select_types2();
    init_update2();
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/count.js
var _a226, _b160, _c8, _SQLiteCountBuilder, SQLiteCountBuilder;
var init_count2 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/count.js"() {
    "use strict";
    init_entity();
    init_sql();
    _SQLiteCountBuilder = class _SQLiteCountBuilder extends (_c8 = SQL, _b160 = entityKind, _a226 = Symbol.toStringTag, _c8) {
      constructor(params) {
        super(_SQLiteCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
        __publicField(this, "sql");
        __publicField(this, _a226, "SQLiteCountBuilderAsync");
        __publicField(this, "session");
        this.params = params;
        this.session = params.session;
        this.sql = _SQLiteCountBuilder.buildCount(
          params.source,
          params.filters
        );
      }
      static buildEmbeddedCount(source, filters) {
        return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
      }
      static buildCount(source, filters) {
        return sql`select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters}`;
      }
      then(onfulfilled, onrejected) {
        return Promise.resolve(this.session.count(this.sql)).then(
          onfulfilled,
          onrejected
        );
      }
      catch(onRejected) {
        return this.then(void 0, onRejected);
      }
      finally(onFinally) {
        return this.then(
          (value) => {
            onFinally?.();
            return value;
          },
          (reason) => {
            onFinally?.();
            throw reason;
          }
        );
      }
    };
    __publicField(_SQLiteCountBuilder, _b160, "SQLiteCountBuilderAsync");
    SQLiteCountBuilder = _SQLiteCountBuilder;
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/query.js
var _a227, RelationalQueryBuilder2, _a228, _b161, SQLiteRelationalQuery, _a229, _b162, SQLiteSyncRelationalQuery;
var init_query2 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/query.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_relations();
    _a227 = entityKind;
    RelationalQueryBuilder2 = class {
      constructor(mode, fullSchema, schema5, tableNamesMap, table6, tableConfig, dialect6, session) {
        this.mode = mode;
        this.fullSchema = fullSchema;
        this.schema = schema5;
        this.tableNamesMap = tableNamesMap;
        this.table = table6;
        this.tableConfig = tableConfig;
        this.dialect = dialect6;
        this.session = session;
      }
      findMany(config) {
        return this.mode === "sync" ? new SQLiteSyncRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config ? config : {},
          "many"
        ) : new SQLiteRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config ? config : {},
          "many"
        );
      }
      findFirst(config) {
        return this.mode === "sync" ? new SQLiteSyncRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config ? { ...config, limit: 1 } : { limit: 1 },
          "first"
        ) : new SQLiteRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config ? { ...config, limit: 1 } : { limit: 1 },
          "first"
        );
      }
    };
    __publicField(RelationalQueryBuilder2, _a227, "SQLiteAsyncRelationalQueryBuilder");
    SQLiteRelationalQuery = class extends (_b161 = QueryPromise, _a228 = entityKind, _b161) {
      constructor(fullSchema, schema5, tableNamesMap, table6, tableConfig, dialect6, session, config, mode) {
        super();
        /** @internal */
        __publicField(this, "mode");
        this.fullSchema = fullSchema;
        this.schema = schema5;
        this.tableNamesMap = tableNamesMap;
        this.table = table6;
        this.tableConfig = tableConfig;
        this.dialect = dialect6;
        this.session = session;
        this.config = config;
        this.mode = mode;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildRelationalQuery({
          fullSchema: this.fullSchema,
          schema: this.schema,
          tableNamesMap: this.tableNamesMap,
          table: this.table,
          tableConfig: this.tableConfig,
          queryConfig: this.config,
          tableAlias: this.tableConfig.tsName
        }).sql;
      }
      /** @internal */
      _prepare(isOneTimeQuery = false) {
        const { query, builtQuery } = this._toSQL();
        return this.session[isOneTimeQuery ? "prepareOneTimeQuery" : "prepareQuery"](
          builtQuery,
          void 0,
          this.mode === "first" ? "get" : "all",
          true,
          (rawRows, mapColumnValue) => {
            const rows = rawRows.map(
              (row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)
            );
            if (this.mode === "first") {
              return rows[0];
            }
            return rows;
          }
        );
      }
      prepare() {
        return this._prepare(false);
      }
      _toSQL() {
        const query = this.dialect.buildRelationalQuery({
          fullSchema: this.fullSchema,
          schema: this.schema,
          tableNamesMap: this.tableNamesMap,
          table: this.table,
          tableConfig: this.tableConfig,
          queryConfig: this.config,
          tableAlias: this.tableConfig.tsName
        });
        const builtQuery = this.dialect.sqlToQuery(query.sql);
        return { query, builtQuery };
      }
      toSQL() {
        return this._toSQL().builtQuery;
      }
      /** @internal */
      executeRaw() {
        if (this.mode === "first") {
          return this._prepare(false).get();
        }
        return this._prepare(false).all();
      }
      async execute() {
        return this.executeRaw();
      }
    };
    __publicField(SQLiteRelationalQuery, _a228, "SQLiteAsyncRelationalQuery");
    SQLiteSyncRelationalQuery = class extends (_b162 = SQLiteRelationalQuery, _a229 = entityKind, _b162) {
      sync() {
        return this.executeRaw();
      }
    };
    __publicField(SQLiteSyncRelationalQuery, _a229, "SQLiteSyncRelationalQuery");
  }
});

// ../drizzle-orm/dist/sqlite-core/query-builders/raw.js
var _a230, _b163, SQLiteRaw;
var init_raw2 = __esm({
  "../drizzle-orm/dist/sqlite-core/query-builders/raw.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    SQLiteRaw = class extends (_b163 = QueryPromise, _a230 = entityKind, _b163) {
      constructor(execute, getSQL, action, dialect6, mapBatchResult) {
        super();
        /** @internal */
        __publicField(this, "config");
        this.execute = execute;
        this.getSQL = getSQL;
        this.dialect = dialect6;
        this.mapBatchResult = mapBatchResult;
        this.config = { action };
      }
      getQuery() {
        return { ...this.dialect.sqlToQuery(this.getSQL()), method: this.config.action };
      }
      mapResult(result, isFromBatch) {
        return isFromBatch ? this.mapBatchResult(result) : result;
      }
      _prepare() {
        return this;
      }
      /** @internal */
      isResponseInArrayMode() {
        return false;
      }
    };
    __publicField(SQLiteRaw, _a230, "SQLiteRaw");
  }
});

// ../drizzle-orm/dist/sqlite-core/db.js
var _a231, BaseSQLiteDatabase;
var init_db2 = __esm({
  "../drizzle-orm/dist/sqlite-core/db.js"() {
    "use strict";
    init_entity();
    init_selection_proxy();
    init_sql();
    init_query_builders2();
    init_subquery();
    init_count2();
    init_query2();
    init_raw2();
    _a231 = entityKind;
    BaseSQLiteDatabase = class {
      constructor(resultKind, dialect6, session, schema5) {
        __publicField(this, "query");
        /**
         * Creates a subquery that defines a temporary named result set as a CTE.
         *
         * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
         *
         * @param alias The alias for the subquery.
         *
         * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
         *
         * @example
         *
         * ```ts
         * // Create a subquery with alias 'sq' and use it in the select query
         * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
         *
         * const result = await db.with(sq).select().from(sq);
         * ```
         *
         * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
         *
         * ```ts
         * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
         * const sq = db.$with('sq').as(db.select({
         *   name: sql<string>`upper(${users.name})`.as('name'),
         * })
         * .from(users));
         *
         * const result = await db.with(sq).select({ name: sq.name }).from(sq);
         * ```
         */
        __publicField(this, "$with", (alias, selection) => {
          const self2 = this;
          const as = (qb) => {
            if (typeof qb === "function") {
              qb = qb(new QueryBuilder2(self2.dialect));
            }
            return new Proxy(
              new WithSubquery(
                qb.getSQL(),
                selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
                alias,
                true
              ),
              new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
            );
          };
          return { as };
        });
        __publicField(this, "$cache");
        this.resultKind = resultKind;
        this.dialect = dialect6;
        this.session = session;
        this._ = schema5 ? {
          schema: schema5.schema,
          fullSchema: schema5.fullSchema,
          tableNamesMap: schema5.tableNamesMap
        } : {
          schema: void 0,
          fullSchema: {},
          tableNamesMap: {}
        };
        this.query = {};
        const query = this.query;
        if (this._.schema) {
          for (const [tableName, columns] of Object.entries(this._.schema)) {
            query[tableName] = new RelationalQueryBuilder2(
              resultKind,
              schema5.fullSchema,
              this._.schema,
              this._.tableNamesMap,
              schema5.fullSchema[tableName],
              columns,
              dialect6,
              session
            );
          }
        }
        this.$cache = { invalidate: async (_params) => {
        } };
      }
      $count(source, filters) {
        return new SQLiteCountBuilder({ source, filters, session: this.session });
      }
      /**
       * Incorporates a previously defined CTE (using `$with`) into the main query.
       *
       * This method allows the main query to reference a temporary named result set.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
       *
       * @param queries The CTEs to incorporate into the main query.
       *
       * @example
       *
       * ```ts
       * // Define a subquery 'sq' as a CTE using $with
       * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
       *
       * // Incorporate the CTE 'sq' into the main query and select from it
       * const result = await db.with(sq).select().from(sq);
       * ```
       */
      with(...queries) {
        const self2 = this;
        function select(fields) {
          return new SQLiteSelectBuilder({
            fields: fields ?? void 0,
            session: self2.session,
            dialect: self2.dialect,
            withList: queries
          });
        }
        function selectDistinct(fields) {
          return new SQLiteSelectBuilder({
            fields: fields ?? void 0,
            session: self2.session,
            dialect: self2.dialect,
            withList: queries,
            distinct: true
          });
        }
        function update(table6) {
          return new SQLiteUpdateBuilder(table6, self2.session, self2.dialect, queries);
        }
        function insert(into) {
          return new SQLiteInsertBuilder(into, self2.session, self2.dialect, queries);
        }
        function delete_(from) {
          return new SQLiteDeleteBase(from, self2.session, self2.dialect, queries);
        }
        return { select, selectDistinct, update, insert, delete: delete_ };
      }
      select(fields) {
        return new SQLiteSelectBuilder({ fields: fields ?? void 0, session: this.session, dialect: this.dialect });
      }
      selectDistinct(fields) {
        return new SQLiteSelectBuilder({
          fields: fields ?? void 0,
          session: this.session,
          dialect: this.dialect,
          distinct: true
        });
      }
      /**
       * Creates an update query.
       *
       * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
       *
       * Use `.set()` method to specify which values to update.
       *
       * See docs: {@link https://orm.drizzle.team/docs/update}
       *
       * @param table The table to update.
       *
       * @example
       *
       * ```ts
       * // Update all rows in the 'cars' table
       * await db.update(cars).set({ color: 'red' });
       *
       * // Update rows with filters and conditions
       * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
       *
       * // Update with returning clause
       * const updatedCar: Car[] = await db.update(cars)
       *   .set({ color: 'red' })
       *   .where(eq(cars.id, 1))
       *   .returning();
       * ```
       */
      update(table6) {
        return new SQLiteUpdateBuilder(table6, this.session, this.dialect);
      }
      /**
       * Creates an insert query.
       *
       * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert}
       *
       * @param table The table to insert into.
       *
       * @example
       *
       * ```ts
       * // Insert one row
       * await db.insert(cars).values({ brand: 'BMW' });
       *
       * // Insert multiple rows
       * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
       *
       * // Insert with returning clause
       * const insertedCar: Car[] = await db.insert(cars)
       *   .values({ brand: 'BMW' })
       *   .returning();
       * ```
       */
      insert(into) {
        return new SQLiteInsertBuilder(into, this.session, this.dialect);
      }
      /**
       * Creates a delete query.
       *
       * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
       *
       * See docs: {@link https://orm.drizzle.team/docs/delete}
       *
       * @param table The table to delete from.
       *
       * @example
       *
       * ```ts
       * // Delete all rows in the 'cars' table
       * await db.delete(cars);
       *
       * // Delete rows with filters and conditions
       * await db.delete(cars).where(eq(cars.color, 'green'));
       *
       * // Delete with returning clause
       * const deletedCar: Car[] = await db.delete(cars)
       *   .where(eq(cars.id, 1))
       *   .returning();
       * ```
       */
      delete(from) {
        return new SQLiteDeleteBase(from, this.session, this.dialect);
      }
      run(query) {
        const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
        if (this.resultKind === "async") {
          return new SQLiteRaw(
            async () => this.session.run(sequel),
            () => sequel,
            "run",
            this.dialect,
            this.session.extractRawRunValueFromBatchResult.bind(this.session)
          );
        }
        return this.session.run(sequel);
      }
      all(query) {
        const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
        if (this.resultKind === "async") {
          return new SQLiteRaw(
            async () => this.session.all(sequel),
            () => sequel,
            "all",
            this.dialect,
            this.session.extractRawAllValueFromBatchResult.bind(this.session)
          );
        }
        return this.session.all(sequel);
      }
      get(query) {
        const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
        if (this.resultKind === "async") {
          return new SQLiteRaw(
            async () => this.session.get(sequel),
            () => sequel,
            "get",
            this.dialect,
            this.session.extractRawGetValueFromBatchResult.bind(this.session)
          );
        }
        return this.session.get(sequel);
      }
      values(query) {
        const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL();
        if (this.resultKind === "async") {
          return new SQLiteRaw(
            async () => this.session.values(sequel),
            () => sequel,
            "values",
            this.dialect,
            this.session.extractRawValuesValueFromBatchResult.bind(this.session)
          );
        }
        return this.session.values(sequel);
      }
      transaction(transaction, config) {
        return this.session.transaction(transaction, config);
      }
    };
    __publicField(BaseSQLiteDatabase, _a231, "BaseSQLiteDatabase");
  }
});

// ../drizzle-orm/dist/sqlite-core/session.js
var _a232, _b164, ExecuteResultSync, _a233, SQLitePreparedQuery, _a234, SQLiteSession, _a235, _b165, SQLiteTransaction;
var init_session2 = __esm({
  "../drizzle-orm/dist/sqlite-core/session.js"() {
    "use strict";
    init_cache();
    init_entity();
    init_errors2();
    init_errors3();
    init_query_promise();
    init_db2();
    ExecuteResultSync = class extends (_b164 = QueryPromise, _a232 = entityKind, _b164) {
      constructor(resultCb) {
        super();
        this.resultCb = resultCb;
      }
      async execute() {
        return this.resultCb();
      }
      sync() {
        return this.resultCb();
      }
    };
    __publicField(ExecuteResultSync, _a232, "ExecuteResultSync");
    _a233 = entityKind;
    SQLitePreparedQuery = class {
      constructor(mode, executeMethod, query, cache, queryMetadata, cacheConfig) {
        /** @internal */
        __publicField(this, "joinsNotNullableMap");
        this.mode = mode;
        this.executeMethod = executeMethod;
        this.query = query;
        this.cache = cache;
        this.queryMetadata = queryMetadata;
        this.cacheConfig = cacheConfig;
        if (cache && cache.strategy() === "all" && cacheConfig === void 0) {
          this.cacheConfig = { enable: true, autoInvalidate: true };
        }
        if (!this.cacheConfig?.enable) {
          this.cacheConfig = void 0;
        }
      }
      /** @internal */
      async queryWithCache(queryString, params, query) {
        if (this.cache === void 0 || is(this.cache, NoopCache) || this.queryMetadata === void 0) {
          try {
            return await query();
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if (this.cacheConfig && !this.cacheConfig.enable) {
          try {
            return await query();
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) {
          try {
            const [res] = await Promise.all([
              query(),
              this.cache.onMutate({ tables: this.queryMetadata.tables })
            ]);
            return res;
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if (!this.cacheConfig) {
          try {
            return await query();
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if (this.queryMetadata.type === "select") {
          const fromCache = await this.cache.get(
            this.cacheConfig.tag ?? await hashQuery(queryString, params),
            this.queryMetadata.tables,
            this.cacheConfig.tag !== void 0,
            this.cacheConfig.autoInvalidate
          );
          if (fromCache === void 0) {
            let result;
            try {
              result = await query();
            } catch (e) {
              throw new DrizzleQueryError(queryString, params, e);
            }
            await this.cache.put(
              this.cacheConfig.tag ?? await hashQuery(queryString, params),
              result,
              // make sure we send tables that were used in a query only if user wants to invalidate it on each write
              this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [],
              this.cacheConfig.tag !== void 0,
              this.cacheConfig.config
            );
            return result;
          }
          return fromCache;
        }
        try {
          return await query();
        } catch (e) {
          throw new DrizzleQueryError(queryString, params, e);
        }
      }
      getQuery() {
        return this.query;
      }
      mapRunResult(result, _isFromBatch) {
        return result;
      }
      mapAllResult(_result, _isFromBatch) {
        throw new Error("Not implemented");
      }
      mapGetResult(_result, _isFromBatch) {
        throw new Error("Not implemented");
      }
      execute(placeholderValues) {
        if (this.mode === "async") {
          return this[this.executeMethod](placeholderValues);
        }
        return new ExecuteResultSync(() => this[this.executeMethod](placeholderValues));
      }
      mapResult(response, isFromBatch) {
        switch (this.executeMethod) {
          case "run": {
            return this.mapRunResult(response, isFromBatch);
          }
          case "all": {
            return this.mapAllResult(response, isFromBatch);
          }
          case "get": {
            return this.mapGetResult(response, isFromBatch);
          }
        }
      }
    };
    __publicField(SQLitePreparedQuery, _a233, "PreparedQuery");
    _a234 = entityKind;
    SQLiteSession = class {
      constructor(dialect6) {
        this.dialect = dialect6;
      }
      prepareOneTimeQuery(query, fields, executeMethod, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) {
        return this.prepareQuery(
          query,
          fields,
          executeMethod,
          isResponseInArrayMode,
          customResultMapper,
          queryMetadata,
          cacheConfig
        );
      }
      run(query) {
        const staticQuery = this.dialect.sqlToQuery(query);
        try {
          return this.prepareOneTimeQuery(staticQuery, void 0, "run", false).run();
        } catch (err) {
          throw new DrizzleError({ cause: err, message: `Failed to run the query '${staticQuery.sql}'` });
        }
      }
      /** @internal */
      extractRawRunValueFromBatchResult(result) {
        return result;
      }
      all(query) {
        return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).all();
      }
      /** @internal */
      extractRawAllValueFromBatchResult(_result) {
        throw new Error("Not implemented");
      }
      get(query) {
        return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).get();
      }
      /** @internal */
      extractRawGetValueFromBatchResult(_result) {
        throw new Error("Not implemented");
      }
      values(query) {
        return this.prepareOneTimeQuery(this.dialect.sqlToQuery(query), void 0, "run", false).values();
      }
      async count(sql2) {
        const result = await this.values(sql2);
        return result[0][0];
      }
      /** @internal */
      extractRawValuesValueFromBatchResult(_result) {
        throw new Error("Not implemented");
      }
    };
    __publicField(SQLiteSession, _a234, "SQLiteSession");
    SQLiteTransaction = class extends (_b165 = BaseSQLiteDatabase, _a235 = entityKind, _b165) {
      constructor(resultType, dialect6, session, schema5, nestedIndex = 0) {
        super(resultType, dialect6, session, schema5);
        this.schema = schema5;
        this.nestedIndex = nestedIndex;
      }
      rollback() {
        throw new TransactionRollbackError();
      }
    };
    __publicField(SQLiteTransaction, _a235, "SQLiteTransaction");
  }
});

// ../drizzle-orm/dist/sqlite-core/subquery.js
var init_subquery3 = __esm({
  "../drizzle-orm/dist/sqlite-core/subquery.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/sqlite-core/view.js
var _a236, ViewBuilderCore, _a237, _b166, ViewBuilder2, _a238, _b167, ManualViewBuilder2, _a239, _b168, SQLiteView2;
var init_view2 = __esm({
  "../drizzle-orm/dist/sqlite-core/view.js"() {
    "use strict";
    init_entity();
    init_selection_proxy();
    init_utils2();
    init_query_builder3();
    init_table3();
    init_view_base2();
    _a236 = entityKind;
    ViewBuilderCore = class {
      constructor(name2) {
        __publicField(this, "config", {});
        this.name = name2;
      }
    };
    __publicField(ViewBuilderCore, _a236, "SQLiteViewBuilderCore");
    ViewBuilder2 = class extends (_b166 = ViewBuilderCore, _a237 = entityKind, _b166) {
      as(qb) {
        if (typeof qb === "function") {
          qb = qb(new QueryBuilder2());
        }
        const selectionProxy = new SelectionProxyHandler({
          alias: this.name,
          sqlBehavior: "error",
          sqlAliasedBehavior: "alias",
          replaceOriginalName: true
        });
        const aliasedSelectedFields = qb.getSelectedFields();
        return new Proxy(
          new SQLiteView2({
            // sqliteConfig: this.config,
            config: {
              name: this.name,
              schema: void 0,
              selectedFields: aliasedSelectedFields,
              query: qb.getSQL().inlineParams()
            }
          }),
          selectionProxy
        );
      }
    };
    __publicField(ViewBuilder2, _a237, "SQLiteViewBuilder");
    ManualViewBuilder2 = class extends (_b167 = ViewBuilderCore, _a238 = entityKind, _b167) {
      constructor(name2, columns) {
        super(name2);
        __publicField(this, "columns");
        this.columns = getTableColumns(sqliteTable(name2, columns));
      }
      existing() {
        return new Proxy(
          new SQLiteView2({
            config: {
              name: this.name,
              schema: void 0,
              selectedFields: this.columns,
              query: void 0
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
      as(query) {
        return new Proxy(
          new SQLiteView2({
            config: {
              name: this.name,
              schema: void 0,
              selectedFields: this.columns,
              query: query.inlineParams()
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
    };
    __publicField(ManualViewBuilder2, _a238, "SQLiteManualViewBuilder");
    SQLiteView2 = class extends (_b168 = SQLiteViewBase, _a239 = entityKind, _b168) {
      constructor({ config }) {
        super(config);
      }
    };
    __publicField(SQLiteView2, _a239, "SQLiteView");
  }
});

// ../drizzle-orm/dist/sqlite-core/index.js
var init_sqlite_core = __esm({
  "../drizzle-orm/dist/sqlite-core/index.js"() {
    "use strict";
    init_alias3();
    init_checks2();
    init_columns2();
    init_db2();
    init_dialect2();
    init_foreign_keys2();
    init_indexes2();
    init_primary_keys2();
    init_query_builders2();
    init_session2();
    init_subquery3();
    init_table3();
    init_unique_constraint2();
    init_utils7();
    init_view2();
  }
});

// src/serializer/sqliteSerializer.ts
function mapSqlToSqliteType(sqlType) {
  const lowered = sqlType.toLowerCase();
  if ([
    "int",
    "integer",
    "integer auto_increment",
    "tinyint",
    "smallint",
    "mediumint",
    "bigint",
    "unsigned big int",
    "int2",
    "int8"
  ].some((it) => lowered.startsWith(it))) {
    return "integer";
  } else if ([
    "character",
    "varchar",
    "varying character",
    "national varying character",
    "nchar",
    "native character",
    "nvarchar",
    "text",
    "clob"
  ].some((it) => lowered.startsWith(it))) {
    const match2 = lowered.match(/\d+/);
    if (match2) {
      return `text(${match2[0]})`;
    }
    return "text";
  } else if (lowered.startsWith("blob")) {
    return "blob";
  } else if (["real", "double", "double precision", "float"].some((it) => lowered.startsWith(it))) {
    return "real";
  } else {
    return "numeric";
  }
}
function extractGeneratedColumns(input) {
  const columns = {};
  const lines = input.split(/,\s*(?![^()]*\))/);
  for (const line2 of lines) {
    if (line2.includes("GENERATED ALWAYS AS")) {
      const parts = line2.trim().split(/\s+/);
      const columnName = parts[0].replace(/[`'"]/g, "");
      const expression = line2.substring(line2.indexOf("("), line2.indexOf(")") + 1).trim();
      const typeIndex = parts.findIndex((part) => part.match(/(stored|virtual)/i));
      let type = "virtual";
      if (typeIndex !== -1) {
        type = parts[typeIndex].replace(/[^a-z]/gi, "").toLowerCase();
      }
      columns[columnName] = {
        columnName,
        expression,
        type
      };
    }
  }
  return columns;
}
function filterIgnoredTablesByField(fieldName) {
  return `${fieldName} != '__drizzle_migrations'
			AND ${fieldName} NOT LIKE '\\_cf\\_%' ESCAPE '\\'
			AND ${fieldName} NOT LIKE '\\_litestream\\_%' ESCAPE '\\'
			AND ${fieldName} NOT LIKE 'libsql\\_%' ESCAPE '\\'
			AND ${fieldName} NOT LIKE 'sqlite\\_%' ESCAPE '\\'`;
}
var generateSqliteSnapshot, fromDatabase2;
var init_sqliteSerializer = __esm({
  "src/serializer/sqliteSerializer.ts"() {
    "use strict";
    init_source();
    init_dist();
    init_sqlite_core();
    init_outputs();
    init_utils();
    init_utils6();
    generateSqliteSnapshot = (tables, views, casing2) => {
      const dialect6 = new SQLiteSyncDialect({ casing: casing2 });
      const result = {};
      const resultViews = {};
      const internal = { indexes: {} };
      for (const table6 of tables) {
        const columnsObject = {};
        const indexesObject = {};
        const foreignKeysObject = {};
        const primaryKeysObject = {};
        const uniqueConstraintObject = {};
        const checkConstraintObject = {};
        const checksInTable = {};
        const {
          name: tableName,
          columns,
          indexes,
          checks,
          foreignKeys: tableForeignKeys,
          primaryKeys,
          uniqueConstraints
        } = getTableConfig2(table6);
        columns.forEach((column6) => {
          const name2 = getColumnCasing(column6, casing2);
          const notNull = column6.notNull;
          const primaryKey = column6.primary;
          const generated = column6.generated;
          const columnToSet = {
            name: name2,
            type: column6.getSQLType(),
            primaryKey,
            notNull,
            autoincrement: is(column6, SQLiteBaseInteger) ? column6.autoIncrement : false,
            generated: generated ? {
              as: is(generated.as, SQL) ? `(${dialect6.sqlToQuery(generated.as, "indexes").sql})` : typeof generated.as === "function" ? `(${dialect6.sqlToQuery(generated.as(), "indexes").sql})` : `(${generated.as})`,
              type: generated.mode ?? "virtual"
            } : void 0
          };
          if (column6.default !== void 0) {
            if (is(column6.default, SQL)) {
              columnToSet.default = sqlToStr(column6.default, casing2);
            } else {
              columnToSet.default = typeof column6.default === "string" ? `'${escapeSingleQuotes(column6.default)}'` : typeof column6.default === "object" || Array.isArray(column6.default) ? `'${JSON.stringify(column6.default)}'` : column6.default;
            }
          }
          columnsObject[name2] = columnToSet;
          if (column6.isUnique) {
            const existingUnique = indexesObject[column6.uniqueName];
            if (typeof existingUnique !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
          The unique constraint ${source_default.underline.blue(
                  column6.uniqueName
                )} on the ${source_default.underline.blue(
                  name2
                )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`)}`
              );
              process.exit(1);
            }
            indexesObject[column6.uniqueName] = {
              name: column6.uniqueName,
              columns: [columnToSet.name],
              isUnique: true
            };
          }
        });
        const foreignKeys = tableForeignKeys.map((fk5) => {
          const tableFrom = tableName;
          const onDelete = fk5.onDelete ?? "no action";
          const onUpdate = fk5.onUpdate ?? "no action";
          const reference = fk5.reference();
          const referenceFT = reference.foreignTable;
          const tableTo = getTableName(referenceFT);
          const originalColumnsFrom = reference.columns.map((it) => it.name);
          const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2));
          const originalColumnsTo = reference.foreignColumns.map((it) => it.name);
          const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2));
          let name2 = fk5.getName();
          if (casing2 !== void 0) {
            for (let i = 0; i < originalColumnsFrom.length; i++) {
              name2 = name2.replace(originalColumnsFrom[i], columnsFrom[i]);
            }
            for (let i = 0; i < originalColumnsTo.length; i++) {
              name2 = name2.replace(originalColumnsTo[i], columnsTo[i]);
            }
          }
          return {
            name: name2,
            tableFrom,
            tableTo,
            columnsFrom,
            columnsTo,
            onDelete,
            onUpdate
          };
        });
        foreignKeys.forEach((it) => {
          foreignKeysObject[it.name] = it;
        });
        indexes.forEach((value) => {
          const columns2 = value.config.columns;
          const name2 = value.config.name;
          let indexColumns = columns2.map((it) => {
            if (is(it, SQL)) {
              const sql2 = dialect6.sqlToQuery(it, "indexes").sql;
              if (typeof internal.indexes[name2] === "undefined") {
                internal.indexes[name2] = {
                  columns: {
                    [sql2]: {
                      isExpression: true
                    }
                  }
                };
              } else {
                if (typeof internal.indexes[name2]?.columns[sql2] === "undefined") {
                  internal.indexes[name2].columns[sql2] = {
                    isExpression: true
                  };
                } else {
                  internal.indexes[name2].columns[sql2].isExpression = true;
                }
              }
              return sql2;
            } else {
              return getColumnCasing(it, casing2);
            }
          });
          let where = void 0;
          if (value.config.where !== void 0) {
            if (is(value.config.where, SQL)) {
              where = dialect6.sqlToQuery(value.config.where).sql;
            }
          }
          indexesObject[name2] = {
            name: name2,
            columns: indexColumns,
            isUnique: value.config.unique ?? false,
            where
          };
        });
        uniqueConstraints?.map((unq) => {
          const columnNames = unq.columns.map((c) => getColumnCasing(c, casing2));
          const name2 = unq.name ?? uniqueKeyName2(table6, columnNames);
          const existingUnique = indexesObject[name2];
          if (typeof existingUnique !== "undefined") {
            console.log(
              `
${withStyle.errorWarning(
                `We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
The unique constraint ${source_default.underline.blue(
                  name2
                )} on the ${source_default.underline.blue(
                  columnNames.join(",")
                )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`
              )}`
            );
            process.exit(1);
          }
          indexesObject[name2] = {
            name: unq.name,
            columns: columnNames,
            isUnique: true
          };
        });
        primaryKeys.forEach((it) => {
          if (it.columns.length > 1) {
            const originalColumnNames = it.columns.map((c) => c.name);
            const columnNames = it.columns.map((c) => getColumnCasing(c, casing2));
            let name2 = it.getName();
            if (casing2 !== void 0) {
              for (let i = 0; i < originalColumnNames.length; i++) {
                name2 = name2.replace(originalColumnNames[i], columnNames[i]);
              }
            }
            primaryKeysObject[name2] = {
              columns: columnNames,
              name: name2
            };
          } else {
            columnsObject[getColumnCasing(it.columns[0], casing2)].primaryKey = true;
          }
        });
        checks.forEach((check) => {
          const checkName = check.name;
          if (typeof checksInTable[tableName] !== "undefined") {
            if (checksInTable[tableName].includes(check.name)) {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated check constraint name in ${source_default.underline.blue(
                    tableName
                  )}. Please rename your check constraint in the ${source_default.underline.blue(
                    tableName
                  )} table`
                )}`
              );
              process.exit(1);
            }
            checksInTable[tableName].push(checkName);
          } else {
            checksInTable[tableName] = [check.name];
          }
          checkConstraintObject[checkName] = {
            name: checkName,
            value: dialect6.sqlToQuery(check.value).sql
          };
        });
        result[tableName] = {
          name: tableName,
          columns: columnsObject,
          indexes: indexesObject,
          foreignKeys: foreignKeysObject,
          compositePrimaryKeys: primaryKeysObject,
          uniqueConstraints: uniqueConstraintObject,
          checkConstraints: checkConstraintObject
        };
      }
      for (const view5 of views) {
        const { name: name2, isExisting, selectedFields, query, schema: schema5 } = getViewConfig2(view5);
        const columnsObject = {};
        const existingView = resultViews[name2];
        if (typeof existingView !== "undefined") {
          console.log(
            `
${withStyle.errorWarning(
              `We've found duplicated view name across ${source_default.underline.blue(
                schema5 ?? "public"
              )} schema. Please rename your view`
            )}`
          );
          process.exit(1);
        }
        for (const key in selectedFields) {
          if (is(selectedFields[key], SQLiteColumn)) {
            const column6 = selectedFields[key];
            const notNull = column6.notNull;
            const primaryKey = column6.primary;
            const generated = column6.generated;
            const columnToSet = {
              name: column6.name,
              type: column6.getSQLType(),
              primaryKey,
              notNull,
              autoincrement: is(column6, SQLiteBaseInteger) ? column6.autoIncrement : false,
              generated: generated ? {
                as: is(generated.as, SQL) ? `(${dialect6.sqlToQuery(generated.as, "indexes").sql})` : typeof generated.as === "function" ? `(${dialect6.sqlToQuery(generated.as(), "indexes").sql})` : `(${generated.as})`,
                type: generated.mode ?? "virtual"
              } : void 0
            };
            if (column6.default !== void 0) {
              if (is(column6.default, SQL)) {
                columnToSet.default = sqlToStr(column6.default, casing2);
              } else {
                columnToSet.default = typeof column6.default === "string" ? `'${column6.default}'` : typeof column6.default === "object" || Array.isArray(column6.default) ? `'${JSON.stringify(column6.default)}'` : column6.default;
              }
            }
            columnsObject[column6.name] = columnToSet;
          }
        }
        resultViews[name2] = {
          columns: columnsObject,
          name: name2,
          isExisting,
          definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql
        };
      }
      return {
        version: "6",
        dialect: "sqlite",
        tables: result,
        views: resultViews,
        enums: {},
        _meta: {
          tables: {},
          columns: {}
        },
        internal
      };
    };
    fromDatabase2 = async (db, tablesFilter = (table6) => true, progressCallback) => {
      const result = {};
      const resultViews = {};
      const columns = await db.query(`SELECT 
		  m.name as "tableName",
		  p.name as "columnName",
		  p.type as "columnType",
		  p."notnull" as "notNull",
		  p.dflt_value as "defaultValue",
		  p.pk as pk,
		  p.hidden as hidden,
		  m.sql,
		  m.type as type
		FROM sqlite_master AS m
		JOIN pragma_table_xinfo(m.name) AS p
		WHERE (m.type = 'table' OR m.type = 'view') 
		  AND ${filterIgnoredTablesByField("m.tbl_name")};`);
      const tablesWithSeq = [];
      const seq = await db.query(`SELECT
		  *
		FROM sqlite_master
		WHERE sql GLOB '*[ *' || CHAR(9) || CHAR(10) || CHAR(13) || ']AUTOINCREMENT[^'']*'
    	  AND ${filterIgnoredTablesByField("tbl_name")};`);
      for (const s of seq) {
        tablesWithSeq.push(s.name);
      }
      let columnsCount = 0;
      let tablesCount = /* @__PURE__ */ new Set();
      let indexesCount = 0;
      let foreignKeysCount = 0;
      let checksCount = 0;
      let viewsCount = 0;
      const tableToPk = {};
      let tableToGeneratedColumnsInfo = {};
      for (const column6 of columns) {
        if (!tablesFilter(column6.tableName)) continue;
        if (column6.type !== "view") {
          columnsCount += 1;
        }
        if (progressCallback) {
          progressCallback("columns", columnsCount, "fetching");
        }
        const tableName = column6.tableName;
        tablesCount.add(tableName);
        if (progressCallback) {
          progressCallback("tables", tablesCount.size, "fetching");
        }
        const columnName = column6.columnName;
        const isNotNull2 = column6.notNull === 1;
        const columnType = column6.columnType;
        const isPrimary = column6.pk !== 0;
        const columnDefault = column6.defaultValue;
        const isAutoincrement = isPrimary && tablesWithSeq.includes(tableName);
        if (isPrimary) {
          if (typeof tableToPk[tableName] === "undefined") {
            tableToPk[tableName] = [columnName];
          } else {
            tableToPk[tableName].push(columnName);
          }
        }
        const table6 = result[tableName];
        if (column6.hidden === 2 || column6.hidden === 3) {
          if (typeof tableToGeneratedColumnsInfo[column6.tableName] === "undefined") {
            tableToGeneratedColumnsInfo[column6.tableName] = extractGeneratedColumns(
              column6.sql
            );
          }
        }
        const newColumn = {
          default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) ? Number(columnDefault) : ["CURRENT_TIME", "CURRENT_DATE", "CURRENT_TIMESTAMP"].includes(
            columnDefault
          ) ? `(${columnDefault})` : columnDefault === "false" ? false : columnDefault === "true" ? true : columnDefault.startsWith("'") && columnDefault.endsWith("'") ? columnDefault : `(${columnDefault})`,
          autoincrement: isAutoincrement,
          name: columnName,
          type: mapSqlToSqliteType(columnType),
          primaryKey: false,
          notNull: isNotNull2,
          generated: tableToGeneratedColumnsInfo[tableName] && tableToGeneratedColumnsInfo[tableName][columnName] ? {
            type: tableToGeneratedColumnsInfo[tableName][columnName].type,
            as: tableToGeneratedColumnsInfo[tableName][columnName].expression
          } : void 0
        };
        if (!table6) {
          result[tableName] = {
            name: tableName,
            columns: {
              [columnName]: newColumn
            },
            compositePrimaryKeys: {},
            indexes: {},
            foreignKeys: {},
            uniqueConstraints: {},
            checkConstraints: {}
          };
        } else {
          result[tableName].columns[columnName] = newColumn;
        }
      }
      for (const [key, value] of Object.entries(tableToPk)) {
        if (value.length > 1) {
          result[key].compositePrimaryKeys = {
            [`${key}_${value.join("_")}_pk`]: {
              columns: value,
              name: `${key}_${value.join("_")}_pk`
            }
          };
        } else if (value.length === 1) {
          result[key].columns[value[0]].primaryKey = true;
        } else {
        }
      }
      if (progressCallback) {
        progressCallback("columns", columnsCount, "done");
        progressCallback("tables", tablesCount.size, "done");
      }
      try {
        const fks = await db.query(`SELECT
			  m.name as "tableFrom",
			  f.id as "id",
			  f."table" as "tableTo",
			  f."from",
			  f."to",
			  f."on_update" as "onUpdate",
			  f."on_delete" as "onDelete",
			  f.seq as "seq"
      		FROM
			  sqlite_master m,
			  pragma_foreign_key_list(m.name) as f
      		WHERE ${filterIgnoredTablesByField("m.tbl_name")};`);
        const fkByTableName = {};
        for (const fkRow of fks) {
          foreignKeysCount += 1;
          if (progressCallback) {
            progressCallback("fks", foreignKeysCount, "fetching");
          }
          const tableName = fkRow.tableFrom;
          const columnName = fkRow.from;
          const refTableName = fkRow.tableTo;
          const refColumnName = fkRow.to;
          const updateRule = fkRow.onUpdate;
          const deleteRule = fkRow.onDelete;
          const sequence = fkRow.seq;
          const id = fkRow.id;
          const tableInResult = result[tableName];
          if (typeof tableInResult === "undefined") continue;
          if (typeof fkByTableName[`${tableName}_${id}`] !== "undefined") {
            fkByTableName[`${tableName}_${id}`].columnsFrom.push(columnName);
            fkByTableName[`${tableName}_${id}`].columnsTo.push(refColumnName);
          } else {
            fkByTableName[`${tableName}_${id}`] = {
              name: "",
              tableFrom: tableName,
              tableTo: refTableName,
              columnsFrom: [columnName],
              columnsTo: [refColumnName],
              onDelete: deleteRule?.toLowerCase(),
              onUpdate: updateRule?.toLowerCase()
            };
          }
          const columnsFrom = fkByTableName[`${tableName}_${id}`].columnsFrom;
          const columnsTo = fkByTableName[`${tableName}_${id}`].columnsTo;
          fkByTableName[`${tableName}_${id}`].name = `${tableName}_${columnsFrom.join(
            "_"
          )}_${refTableName}_${columnsTo.join("_")}_fk`;
        }
        for (const idx of Object.keys(fkByTableName)) {
          const value = fkByTableName[idx];
          result[value.tableFrom].foreignKeys[value.name] = value;
        }
      } catch (e) {
      }
      if (progressCallback) {
        progressCallback("fks", foreignKeysCount, "done");
      }
      const idxs = await db.query(`SELECT 
    	  m.tbl_name as tableName,
    	  il.name as indexName,
    	  ii.name as columnName,
    	  il.[unique] as isUnique,
    	  il.seq as seq
		FROM 
		  sqlite_master AS m,
    	  pragma_index_list(m.name) AS il,
    	  pragma_index_info(il.name) AS ii
		WHERE 
		  m.type = 'table' 
    	  AND il.name NOT LIKE 'sqlite\\_autoindex\\_%' ESCAPE '\\'
    	  AND ${filterIgnoredTablesByField("m.tbl_name")};`);
      for (const idxRow of idxs) {
        const tableName = idxRow.tableName;
        const constraintName = idxRow.indexName;
        const columnName = idxRow.columnName;
        const isUnique = idxRow.isUnique === 1;
        const tableInResult = result[tableName];
        if (typeof tableInResult === "undefined") continue;
        indexesCount += 1;
        if (progressCallback) {
          progressCallback("indexes", indexesCount, "fetching");
        }
        if (typeof tableInResult.indexes[constraintName] !== "undefined" && columnName) {
          tableInResult.indexes[constraintName].columns.push(columnName);
        } else {
          tableInResult.indexes[constraintName] = {
            name: constraintName,
            columns: columnName ? [columnName] : [],
            isUnique
          };
        }
      }
      if (progressCallback) {
        progressCallback("indexes", indexesCount, "done");
        progressCallback("enums", 0, "done");
      }
      const views = await db.query(
        `SELECT name AS view_name, sql AS sql FROM sqlite_master WHERE type = 'view';`
      );
      viewsCount = views.length;
      if (progressCallback) {
        progressCallback("views", viewsCount, "fetching");
      }
      for (const view5 of views) {
        const viewName = view5["view_name"];
        const sql2 = view5["sql"];
        const regex = new RegExp(`\\bAS\\b\\s+(SELECT.+)$`, "i");
        const match2 = sql2.match(regex);
        if (!match2) {
          console.log("Could not process view");
          process.exit(1);
        }
        const viewDefinition = match2[1];
        const columns2 = result[viewName].columns;
        delete result[viewName];
        resultViews[viewName] = {
          columns: columns2,
          isExisting: false,
          name: viewName,
          definition: viewDefinition
        };
      }
      if (progressCallback) {
        progressCallback("views", viewsCount, "done");
      }
      const namedCheckPattern = /CONSTRAINT\s*["']?(\w+)["']?\s*CHECK\s*\((.*?)\)/gi;
      const unnamedCheckPattern = /CHECK\s*\((.*?)\)/gi;
      let checkCounter = 0;
      const checkConstraints = {};
      const checks = await db.query(`SELECT
		  name as "tableName",
		  sql as "sql"
		FROM sqlite_master 
		WHERE type = 'table'
		  AND ${filterIgnoredTablesByField("tbl_name")};`);
      for (const check of checks) {
        if (!tablesFilter(check.tableName)) continue;
        const { tableName, sql: sql2 } = check;
        let namedChecks = [...sql2.matchAll(namedCheckPattern)];
        if (namedChecks.length > 0) {
          namedChecks.forEach(([_2, checkName, checkValue]) => {
            checkConstraints[checkName] = {
              name: checkName,
              value: checkValue.trim()
            };
          });
        } else {
          let unnamedChecks = [...sql2.matchAll(unnamedCheckPattern)];
          unnamedChecks.forEach(([_2, checkValue]) => {
            let checkName = `${tableName}_check_${++checkCounter}`;
            checkConstraints[checkName] = {
              name: checkName,
              value: checkValue.trim()
            };
          });
        }
        checksCount += Object.values(checkConstraints).length;
        if (progressCallback) {
          progressCallback("checks", checksCount, "fetching");
        }
        const table6 = result[tableName];
        if (!table6) {
          result[tableName] = {
            name: tableName,
            columns: {},
            compositePrimaryKeys: {},
            indexes: {},
            foreignKeys: {},
            uniqueConstraints: {},
            checkConstraints
          };
        } else {
          result[tableName].checkConstraints = checkConstraints;
        }
      }
      if (progressCallback) {
        progressCallback("checks", checksCount, "done");
      }
      return {
        version: "6",
        dialect: "sqlite",
        tables: result,
        views: resultViews,
        enums: {},
        _meta: {
          tables: {},
          columns: {}
        }
      };
    };
  }
});

// src/extensions/getTablesFilterByExtensions.ts
var getTablesFilterByExtensions;
var init_getTablesFilterByExtensions = __esm({
  "src/extensions/getTablesFilterByExtensions.ts"() {
    "use strict";
    getTablesFilterByExtensions = ({
      extensionsFilters,
      dialect: dialect6
    }) => {
      if (extensionsFilters) {
        if (extensionsFilters.includes("postgis") && dialect6 === "postgresql") {
          return ["!geography_columns", "!geometry_columns", "!spatial_ref_sys"];
        }
      }
      return [];
    };
  }
});

// ../drizzle-orm/dist/mysql-core/alias.js
var init_alias4 = __esm({
  "../drizzle-orm/dist/mysql-core/alias.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/mysql-core/checks.js
var _a240, CheckBuilder3, _a241, Check3;
var init_checks3 = __esm({
  "../drizzle-orm/dist/mysql-core/checks.js"() {
    "use strict";
    init_entity();
    _a240 = entityKind;
    CheckBuilder3 = class {
      constructor(name2, value) {
        __publicField(this, "brand");
        this.name = name2;
        this.value = value;
      }
      /** @internal */
      build(table6) {
        return new Check3(table6, this);
      }
    };
    __publicField(CheckBuilder3, _a240, "MySqlCheckBuilder");
    _a241 = entityKind;
    Check3 = class {
      constructor(table6, builder) {
        __publicField(this, "name");
        __publicField(this, "value");
        this.table = table6;
        this.name = builder.name;
        this.value = builder.value;
      }
    };
    __publicField(Check3, _a241, "MySqlCheck");
  }
});

// ../drizzle-orm/dist/mysql-core/foreign-keys.js
var _a242, ForeignKeyBuilder3, _a243, ForeignKey3;
var init_foreign_keys3 = __esm({
  "../drizzle-orm/dist/mysql-core/foreign-keys.js"() {
    "use strict";
    init_entity();
    init_table_utils();
    _a242 = entityKind;
    ForeignKeyBuilder3 = class {
      constructor(config, actions) {
        /** @internal */
        __publicField(this, "reference");
        /** @internal */
        __publicField(this, "_onUpdate");
        /** @internal */
        __publicField(this, "_onDelete");
        this.reference = () => {
          const { name: name2, columns, foreignColumns } = config();
          return { name: name2, columns, foreignTable: foreignColumns[0].table, foreignColumns };
        };
        if (actions) {
          this._onUpdate = actions.onUpdate;
          this._onDelete = actions.onDelete;
        }
      }
      onUpdate(action) {
        this._onUpdate = action;
        return this;
      }
      onDelete(action) {
        this._onDelete = action;
        return this;
      }
      /** @internal */
      build(table6) {
        return new ForeignKey3(table6, this);
      }
    };
    __publicField(ForeignKeyBuilder3, _a242, "MySqlForeignKeyBuilder");
    _a243 = entityKind;
    ForeignKey3 = class {
      constructor(table6, builder) {
        __publicField(this, "reference");
        __publicField(this, "onUpdate");
        __publicField(this, "onDelete");
        this.table = table6;
        this.reference = builder.reference;
        this.onUpdate = builder._onUpdate;
        this.onDelete = builder._onDelete;
      }
      getName() {
        const { name: name2, columns, foreignColumns } = this.reference();
        const columnNames = columns.map((column6) => column6.name);
        const foreignColumnNames = foreignColumns.map((column6) => column6.name);
        const chunks = [
          this.table[TableName],
          ...columnNames,
          foreignColumns[0].table[TableName],
          ...foreignColumnNames
        ];
        return name2 ?? `${chunks.join("_")}_fk`;
      }
    };
    __publicField(ForeignKey3, _a243, "MySqlForeignKey");
  }
});

// ../drizzle-orm/dist/mysql-core/unique-constraint.js
function uniqueKeyName3(table6, columns) {
  return `${table6[TableName]}_${columns.join("_")}_unique`;
}
var _a244, UniqueConstraintBuilder3, _a245, UniqueOnConstraintBuilder3, _a246, UniqueConstraint3;
var init_unique_constraint3 = __esm({
  "../drizzle-orm/dist/mysql-core/unique-constraint.js"() {
    "use strict";
    init_entity();
    init_table_utils();
    _a244 = entityKind;
    UniqueConstraintBuilder3 = class {
      constructor(columns, name2) {
        /** @internal */
        __publicField(this, "columns");
        this.name = name2;
        this.columns = columns;
      }
      /** @internal */
      build(table6) {
        return new UniqueConstraint3(table6, this.columns, this.name);
      }
    };
    __publicField(UniqueConstraintBuilder3, _a244, "MySqlUniqueConstraintBuilder");
    _a245 = entityKind;
    UniqueOnConstraintBuilder3 = class {
      constructor(name2) {
        /** @internal */
        __publicField(this, "name");
        this.name = name2;
      }
      on(...columns) {
        return new UniqueConstraintBuilder3(columns, this.name);
      }
    };
    __publicField(UniqueOnConstraintBuilder3, _a245, "MySqlUniqueOnConstraintBuilder");
    _a246 = entityKind;
    UniqueConstraint3 = class {
      constructor(table6, columns, name2) {
        __publicField(this, "columns");
        __publicField(this, "name");
        __publicField(this, "nullsNotDistinct", false);
        this.table = table6;
        this.columns = columns;
        this.name = name2 ?? uniqueKeyName3(this.table, this.columns.map((column6) => column6.name));
      }
      getName() {
        return this.name;
      }
    };
    __publicField(UniqueConstraint3, _a246, "MySqlUniqueConstraint");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/common.js
var _a247, _b169, MySqlColumnBuilder, _a248, _b170, MySqlColumn, _a249, _b171, MySqlColumnBuilderWithAutoIncrement, _a250, _b172, MySqlColumnWithAutoIncrement;
var init_common4 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/common.js"() {
    "use strict";
    init_column_builder();
    init_column();
    init_entity();
    init_foreign_keys3();
    init_unique_constraint3();
    MySqlColumnBuilder = class extends (_b169 = ColumnBuilder, _a247 = entityKind, _b169) {
      constructor() {
        super(...arguments);
        __publicField(this, "foreignKeyConfigs", []);
      }
      references(ref, actions = {}) {
        this.foreignKeyConfigs.push({ ref, actions });
        return this;
      }
      unique(name2) {
        this.config.isUnique = true;
        this.config.uniqueName = name2;
        return this;
      }
      generatedAlwaysAs(as, config) {
        this.config.generated = {
          as,
          type: "always",
          mode: config?.mode ?? "virtual"
        };
        return this;
      }
      /** @internal */
      buildForeignKeys(column6, table6) {
        return this.foreignKeyConfigs.map(({ ref, actions }) => {
          return ((ref2, actions2) => {
            const builder = new ForeignKeyBuilder3(() => {
              const foreignColumn = ref2();
              return { columns: [column6], foreignColumns: [foreignColumn] };
            });
            if (actions2.onUpdate) {
              builder.onUpdate(actions2.onUpdate);
            }
            if (actions2.onDelete) {
              builder.onDelete(actions2.onDelete);
            }
            return builder.build(table6);
          })(ref, actions);
        });
      }
    };
    __publicField(MySqlColumnBuilder, _a247, "MySqlColumnBuilder");
    MySqlColumn = class extends (_b170 = Column2, _a248 = entityKind, _b170) {
      constructor(table6, config) {
        if (!config.uniqueName) {
          config.uniqueName = uniqueKeyName3(table6, [config.name]);
        }
        super(table6, config);
        this.table = table6;
      }
    };
    __publicField(MySqlColumn, _a248, "MySqlColumn");
    MySqlColumnBuilderWithAutoIncrement = class extends (_b171 = MySqlColumnBuilder, _a249 = entityKind, _b171) {
      constructor(name2, dataType, columnType) {
        super(name2, dataType, columnType);
        this.config.autoIncrement = false;
      }
      autoincrement() {
        this.config.autoIncrement = true;
        this.config.hasDefault = true;
        return this;
      }
    };
    __publicField(MySqlColumnBuilderWithAutoIncrement, _a249, "MySqlColumnBuilderWithAutoIncrement");
    MySqlColumnWithAutoIncrement = class extends (_b172 = MySqlColumn, _a250 = entityKind, _b172) {
      constructor() {
        super(...arguments);
        __publicField(this, "autoIncrement", this.config.autoIncrement);
      }
    };
    __publicField(MySqlColumnWithAutoIncrement, _a250, "MySqlColumnWithAutoIncrement");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/bigint.js
function bigint2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config.mode === "number") {
    return new MySqlBigInt53Builder(name2, config.unsigned);
  }
  return new MySqlBigInt64Builder(name2, config.unsigned);
}
var _a251, _b173, MySqlBigInt53Builder, _a252, _b174, MySqlBigInt53, _a253, _b175, MySqlBigInt64Builder, _a254, _b176, MySqlBigInt64;
var init_bigint2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/bigint.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlBigInt53Builder = class extends (_b173 = MySqlColumnBuilderWithAutoIncrement, _a251 = entityKind, _b173) {
      constructor(name2, unsigned = false) {
        super(name2, "number", "MySqlBigInt53");
        this.config.unsigned = unsigned;
      }
      /** @internal */
      build(table6) {
        return new MySqlBigInt53(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlBigInt53Builder, _a251, "MySqlBigInt53Builder");
    MySqlBigInt53 = class extends (_b174 = MySqlColumnWithAutoIncrement, _a252 = entityKind, _b174) {
      getSQLType() {
        return `bigint${this.config.unsigned ? " unsigned" : ""}`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "number") {
          return value;
        }
        return Number(value);
      }
    };
    __publicField(MySqlBigInt53, _a252, "MySqlBigInt53");
    MySqlBigInt64Builder = class extends (_b175 = MySqlColumnBuilderWithAutoIncrement, _a253 = entityKind, _b175) {
      constructor(name2, unsigned = false) {
        super(name2, "bigint", "MySqlBigInt64");
        this.config.unsigned = unsigned;
      }
      /** @internal */
      build(table6) {
        return new MySqlBigInt64(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlBigInt64Builder, _a253, "MySqlBigInt64Builder");
    MySqlBigInt64 = class extends (_b176 = MySqlColumnWithAutoIncrement, _a254 = entityKind, _b176) {
      getSQLType() {
        return `bigint${this.config.unsigned ? " unsigned" : ""}`;
      }
      // eslint-disable-next-line unicorn/prefer-native-coercion-functions
      mapFromDriverValue(value) {
        return BigInt(value);
      }
    };
    __publicField(MySqlBigInt64, _a254, "MySqlBigInt64");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/binary.js
function binary(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlBinaryBuilder(name2, config.length);
}
var _a255, _b177, MySqlBinaryBuilder, _a256, _b178, MySqlBinary;
var init_binary = __esm({
  "../drizzle-orm/dist/mysql-core/columns/binary.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlBinaryBuilder = class extends (_b177 = MySqlColumnBuilder, _a255 = entityKind, _b177) {
      constructor(name2, length) {
        super(name2, "string", "MySqlBinary");
        this.config.length = length;
      }
      /** @internal */
      build(table6) {
        return new MySqlBinary(table6, this.config);
      }
    };
    __publicField(MySqlBinaryBuilder, _a255, "MySqlBinaryBuilder");
    MySqlBinary = class extends (_b178 = MySqlColumn, _a256 = entityKind, _b178) {
      constructor() {
        super(...arguments);
        __publicField(this, "length", this.config.length);
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") return value;
        if (Buffer.isBuffer(value)) return value.toString();
        const str = [];
        for (const v of value) {
          str.push(v === 49 ? "1" : "0");
        }
        return str.join("");
      }
      getSQLType() {
        return this.length === void 0 ? `binary` : `binary(${this.length})`;
      }
    };
    __publicField(MySqlBinary, _a256, "MySqlBinary");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/boolean.js
function boolean2(name2) {
  return new MySqlBooleanBuilder(name2 ?? "");
}
var _a257, _b179, MySqlBooleanBuilder, _a258, _b180, MySqlBoolean;
var init_boolean2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/boolean.js"() {
    "use strict";
    init_entity();
    init_common4();
    MySqlBooleanBuilder = class extends (_b179 = MySqlColumnBuilder, _a257 = entityKind, _b179) {
      constructor(name2) {
        super(name2, "boolean", "MySqlBoolean");
      }
      /** @internal */
      build(table6) {
        return new MySqlBoolean(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlBooleanBuilder, _a257, "MySqlBooleanBuilder");
    MySqlBoolean = class extends (_b180 = MySqlColumn, _a258 = entityKind, _b180) {
      getSQLType() {
        return "boolean";
      }
      mapFromDriverValue(value) {
        if (typeof value === "boolean") {
          return value;
        }
        return value === 1;
      }
    };
    __publicField(MySqlBoolean, _a258, "MySqlBoolean");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/char.js
function char2(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlCharBuilder(name2, config);
}
var _a259, _b181, MySqlCharBuilder, _a260, _b182, MySqlChar;
var init_char2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/char.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlCharBuilder = class extends (_b181 = MySqlColumnBuilder, _a259 = entityKind, _b181) {
      constructor(name2, config) {
        super(name2, "string", "MySqlChar");
        this.config.length = config.length;
        this.config.enum = config.enum;
      }
      /** @internal */
      build(table6) {
        return new MySqlChar(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlCharBuilder, _a259, "MySqlCharBuilder");
    MySqlChar = class extends (_b182 = MySqlColumn, _a260 = entityKind, _b182) {
      constructor() {
        super(...arguments);
        __publicField(this, "length", this.config.length);
        __publicField(this, "enumValues", this.config.enum);
      }
      getSQLType() {
        return this.length === void 0 ? `char` : `char(${this.length})`;
      }
    };
    __publicField(MySqlChar, _a260, "MySqlChar");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/custom.js
function customType3(customTypeParams) {
  return (a, b) => {
    const { name: name2, config } = getColumnNameAndConfig(a, b);
    return new MySqlCustomColumnBuilder(name2, config, customTypeParams);
  };
}
var _a261, _b183, MySqlCustomColumnBuilder, _a262, _b184, MySqlCustomColumn;
var init_custom3 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/custom.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlCustomColumnBuilder = class extends (_b183 = MySqlColumnBuilder, _a261 = entityKind, _b183) {
      constructor(name2, fieldConfig, customTypeParams) {
        super(name2, "custom", "MySqlCustomColumn");
        this.config.fieldConfig = fieldConfig;
        this.config.customTypeParams = customTypeParams;
      }
      /** @internal */
      build(table6) {
        return new MySqlCustomColumn(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlCustomColumnBuilder, _a261, "MySqlCustomColumnBuilder");
    MySqlCustomColumn = class extends (_b184 = MySqlColumn, _a262 = entityKind, _b184) {
      constructor(table6, config) {
        super(table6, config);
        __publicField(this, "sqlName");
        __publicField(this, "mapTo");
        __publicField(this, "mapFrom");
        this.sqlName = config.customTypeParams.dataType(config.fieldConfig);
        this.mapTo = config.customTypeParams.toDriver;
        this.mapFrom = config.customTypeParams.fromDriver;
      }
      getSQLType() {
        return this.sqlName;
      }
      mapFromDriverValue(value) {
        return typeof this.mapFrom === "function" ? this.mapFrom(value) : value;
      }
      mapToDriverValue(value) {
        return typeof this.mapTo === "function" ? this.mapTo(value) : value;
      }
    };
    __publicField(MySqlCustomColumn, _a262, "MySqlCustomColumn");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/date.js
function date2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config?.mode === "string") {
    return new MySqlDateStringBuilder(name2);
  }
  return new MySqlDateBuilder(name2);
}
var _a263, _b185, MySqlDateBuilder, _a264, _b186, MySqlDate, _a265, _b187, MySqlDateStringBuilder, _a266, _b188, MySqlDateString;
var init_date2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/date.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlDateBuilder = class extends (_b185 = MySqlColumnBuilder, _a263 = entityKind, _b185) {
      constructor(name2) {
        super(name2, "date", "MySqlDate");
      }
      /** @internal */
      build(table6) {
        return new MySqlDate(table6, this.config);
      }
    };
    __publicField(MySqlDateBuilder, _a263, "MySqlDateBuilder");
    MySqlDate = class extends (_b186 = MySqlColumn, _a264 = entityKind, _b186) {
      constructor(table6, config) {
        super(table6, config);
      }
      getSQLType() {
        return `date`;
      }
      mapFromDriverValue(value) {
        return new Date(value);
      }
    };
    __publicField(MySqlDate, _a264, "MySqlDate");
    MySqlDateStringBuilder = class extends (_b187 = MySqlColumnBuilder, _a265 = entityKind, _b187) {
      constructor(name2) {
        super(name2, "string", "MySqlDateString");
      }
      /** @internal */
      build(table6) {
        return new MySqlDateString(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlDateStringBuilder, _a265, "MySqlDateStringBuilder");
    MySqlDateString = class extends (_b188 = MySqlColumn, _a266 = entityKind, _b188) {
      constructor(table6, config) {
        super(table6, config);
      }
      getSQLType() {
        return `date`;
      }
    };
    __publicField(MySqlDateString, _a266, "MySqlDateString");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/datetime.js
function datetime(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config?.mode === "string") {
    return new MySqlDateTimeStringBuilder(name2, config);
  }
  return new MySqlDateTimeBuilder(name2, config);
}
var _a267, _b189, MySqlDateTimeBuilder, _a268, _b190, MySqlDateTime, _a269, _b191, MySqlDateTimeStringBuilder, _a270, _b192, MySqlDateTimeString;
var init_datetime = __esm({
  "../drizzle-orm/dist/mysql-core/columns/datetime.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlDateTimeBuilder = class extends (_b189 = MySqlColumnBuilder, _a267 = entityKind, _b189) {
      constructor(name2, config) {
        super(name2, "date", "MySqlDateTime");
        this.config.fsp = config?.fsp;
      }
      /** @internal */
      build(table6) {
        return new MySqlDateTime(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlDateTimeBuilder, _a267, "MySqlDateTimeBuilder");
    MySqlDateTime = class extends (_b190 = MySqlColumn, _a268 = entityKind, _b190) {
      constructor(table6, config) {
        super(table6, config);
        __publicField(this, "fsp");
        this.fsp = config.fsp;
      }
      getSQLType() {
        const precision = this.fsp === void 0 ? "" : `(${this.fsp})`;
        return `datetime${precision}`;
      }
      mapToDriverValue(value) {
        return value.toISOString().replace("T", " ").replace("Z", "");
      }
      mapFromDriverValue(value) {
        return /* @__PURE__ */ new Date(value.replace(" ", "T") + "Z");
      }
    };
    __publicField(MySqlDateTime, _a268, "MySqlDateTime");
    MySqlDateTimeStringBuilder = class extends (_b191 = MySqlColumnBuilder, _a269 = entityKind, _b191) {
      constructor(name2, config) {
        super(name2, "string", "MySqlDateTimeString");
        this.config.fsp = config?.fsp;
      }
      /** @internal */
      build(table6) {
        return new MySqlDateTimeString(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlDateTimeStringBuilder, _a269, "MySqlDateTimeStringBuilder");
    MySqlDateTimeString = class extends (_b192 = MySqlColumn, _a270 = entityKind, _b192) {
      constructor(table6, config) {
        super(table6, config);
        __publicField(this, "fsp");
        this.fsp = config.fsp;
      }
      getSQLType() {
        const precision = this.fsp === void 0 ? "" : `(${this.fsp})`;
        return `datetime${precision}`;
      }
    };
    __publicField(MySqlDateTimeString, _a270, "MySqlDateTimeString");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/decimal.js
function decimal(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  const mode = config?.mode;
  return mode === "number" ? new MySqlDecimalNumberBuilder(name2, config) : mode === "bigint" ? new MySqlDecimalBigIntBuilder(name2, config) : new MySqlDecimalBuilder(name2, config);
}
var _a271, _b193, MySqlDecimalBuilder, _a272, _b194, MySqlDecimal, _a273, _b195, MySqlDecimalNumberBuilder, _a274, _b196, MySqlDecimalNumber, _a275, _b197, MySqlDecimalBigIntBuilder, _a276, _b198, MySqlDecimalBigInt;
var init_decimal = __esm({
  "../drizzle-orm/dist/mysql-core/columns/decimal.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlDecimalBuilder = class extends (_b193 = MySqlColumnBuilderWithAutoIncrement, _a271 = entityKind, _b193) {
      constructor(name2, config) {
        super(name2, "string", "MySqlDecimal");
        this.config.precision = config?.precision;
        this.config.scale = config?.scale;
        this.config.unsigned = config?.unsigned;
      }
      /** @internal */
      build(table6) {
        return new MySqlDecimal(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlDecimalBuilder, _a271, "MySqlDecimalBuilder");
    MySqlDecimal = class extends (_b194 = MySqlColumnWithAutoIncrement, _a272 = entityKind, _b194) {
      constructor() {
        super(...arguments);
        __publicField(this, "precision", this.config.precision);
        __publicField(this, "scale", this.config.scale);
        __publicField(this, "unsigned", this.config.unsigned);
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") return value;
        return String(value);
      }
      getSQLType() {
        let type = "";
        if (this.precision !== void 0 && this.scale !== void 0) {
          type += `decimal(${this.precision},${this.scale})`;
        } else if (this.precision === void 0) {
          type += "decimal";
        } else {
          type += `decimal(${this.precision})`;
        }
        type = type === "decimal(10,0)" || type === "decimal(10)" ? "decimal" : type;
        return this.unsigned ? `${type} unsigned` : type;
      }
    };
    __publicField(MySqlDecimal, _a272, "MySqlDecimal");
    MySqlDecimalNumberBuilder = class extends (_b195 = MySqlColumnBuilderWithAutoIncrement, _a273 = entityKind, _b195) {
      constructor(name2, config) {
        super(name2, "number", "MySqlDecimalNumber");
        this.config.precision = config?.precision;
        this.config.scale = config?.scale;
        this.config.unsigned = config?.unsigned;
      }
      /** @internal */
      build(table6) {
        return new MySqlDecimalNumber(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlDecimalNumberBuilder, _a273, "MySqlDecimalNumberBuilder");
    MySqlDecimalNumber = class extends (_b196 = MySqlColumnWithAutoIncrement, _a274 = entityKind, _b196) {
      constructor() {
        super(...arguments);
        __publicField(this, "precision", this.config.precision);
        __publicField(this, "scale", this.config.scale);
        __publicField(this, "unsigned", this.config.unsigned);
        __publicField(this, "mapToDriverValue", String);
      }
      mapFromDriverValue(value) {
        if (typeof value === "number") return value;
        return Number(value);
      }
      getSQLType() {
        let type = "";
        if (this.precision !== void 0 && this.scale !== void 0) {
          type += `decimal(${this.precision},${this.scale})`;
        } else if (this.precision === void 0) {
          type += "decimal";
        } else {
          type += `decimal(${this.precision})`;
        }
        type = type === "decimal(10,0)" || type === "decimal(10)" ? "decimal" : type;
        return this.unsigned ? `${type} unsigned` : type;
      }
    };
    __publicField(MySqlDecimalNumber, _a274, "MySqlDecimalNumber");
    MySqlDecimalBigIntBuilder = class extends (_b197 = MySqlColumnBuilderWithAutoIncrement, _a275 = entityKind, _b197) {
      constructor(name2, config) {
        super(name2, "bigint", "MySqlDecimalBigInt");
        this.config.precision = config?.precision;
        this.config.scale = config?.scale;
        this.config.unsigned = config?.unsigned;
      }
      /** @internal */
      build(table6) {
        return new MySqlDecimalBigInt(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlDecimalBigIntBuilder, _a275, "MySqlDecimalBigIntBuilder");
    MySqlDecimalBigInt = class extends (_b198 = MySqlColumnWithAutoIncrement, _a276 = entityKind, _b198) {
      constructor() {
        super(...arguments);
        __publicField(this, "precision", this.config.precision);
        __publicField(this, "scale", this.config.scale);
        __publicField(this, "unsigned", this.config.unsigned);
        __publicField(this, "mapFromDriverValue", BigInt);
        __publicField(this, "mapToDriverValue", String);
      }
      getSQLType() {
        let type = "";
        if (this.precision !== void 0 && this.scale !== void 0) {
          type += `decimal(${this.precision},${this.scale})`;
        } else if (this.precision === void 0) {
          type += "decimal";
        } else {
          type += `decimal(${this.precision})`;
        }
        type = type === "decimal(10,0)" || type === "decimal(10)" ? "decimal" : type;
        return this.unsigned ? `${type} unsigned` : type;
      }
    };
    __publicField(MySqlDecimalBigInt, _a276, "MySqlDecimalBigInt");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/double.js
function double(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlDoubleBuilder(name2, config);
}
var _a277, _b199, MySqlDoubleBuilder, _a278, _b200, MySqlDouble;
var init_double = __esm({
  "../drizzle-orm/dist/mysql-core/columns/double.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlDoubleBuilder = class extends (_b199 = MySqlColumnBuilderWithAutoIncrement, _a277 = entityKind, _b199) {
      constructor(name2, config) {
        super(name2, "number", "MySqlDouble");
        this.config.precision = config?.precision;
        this.config.scale = config?.scale;
        this.config.unsigned = config?.unsigned;
      }
      /** @internal */
      build(table6) {
        return new MySqlDouble(table6, this.config);
      }
    };
    __publicField(MySqlDoubleBuilder, _a277, "MySqlDoubleBuilder");
    MySqlDouble = class extends (_b200 = MySqlColumnWithAutoIncrement, _a278 = entityKind, _b200) {
      constructor() {
        super(...arguments);
        __publicField(this, "precision", this.config.precision);
        __publicField(this, "scale", this.config.scale);
        __publicField(this, "unsigned", this.config.unsigned);
      }
      getSQLType() {
        let type = "";
        if (this.precision !== void 0 && this.scale !== void 0) {
          type += `double(${this.precision},${this.scale})`;
        } else if (this.precision === void 0) {
          type += "double";
        } else {
          type += `double(${this.precision})`;
        }
        return this.unsigned ? `${type} unsigned` : type;
      }
    };
    __publicField(MySqlDouble, _a278, "MySqlDouble");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/enum.js
function mysqlEnum(a, b) {
  if (typeof a === "string" && Array.isArray(b) || Array.isArray(a)) {
    const name2 = typeof a === "string" && a.length > 0 ? a : "";
    const values = (typeof a === "string" ? b : a) ?? [];
    if (values.length === 0) {
      throw new Error(`You have an empty array for "${name2}" enum values`);
    }
    return new MySqlEnumColumnBuilder(name2, values);
  }
  if (typeof a === "string" && typeof b === "object" || typeof a === "object") {
    const name2 = typeof a === "object" ? "" : a;
    const values = typeof a === "object" ? Object.values(a) : typeof b === "object" ? Object.values(b) : [];
    if (values.length === 0) {
      throw new Error(`You have an empty array for "${name2}" enum values`);
    }
    return new MySqlEnumObjectColumnBuilder(name2, values);
  }
}
var _a279, _b201, MySqlEnumColumnBuilder, _a280, _b202, MySqlEnumColumn, _a281, _b203, MySqlEnumObjectColumnBuilder, _a282, _b204, MySqlEnumObjectColumn;
var init_enum2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/enum.js"() {
    "use strict";
    init_entity();
    init_common4();
    MySqlEnumColumnBuilder = class extends (_b201 = MySqlColumnBuilder, _a279 = entityKind, _b201) {
      constructor(name2, values) {
        super(name2, "string", "MySqlEnumColumn");
        this.config.enumValues = values;
      }
      /** @internal */
      build(table6) {
        return new MySqlEnumColumn(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlEnumColumnBuilder, _a279, "MySqlEnumColumnBuilder");
    MySqlEnumColumn = class extends (_b202 = MySqlColumn, _a280 = entityKind, _b202) {
      constructor() {
        super(...arguments);
        __publicField(this, "enumValues", this.config.enumValues);
      }
      getSQLType() {
        return `enum(${this.enumValues.map((value) => `'${value}'`).join(",")})`;
      }
    };
    __publicField(MySqlEnumColumn, _a280, "MySqlEnumColumn");
    MySqlEnumObjectColumnBuilder = class extends (_b203 = MySqlColumnBuilder, _a281 = entityKind, _b203) {
      constructor(name2, values) {
        super(name2, "string", "MySqlEnumObjectColumn");
        this.config.enumValues = values;
      }
      /** @internal */
      build(table6) {
        return new MySqlEnumObjectColumn(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlEnumObjectColumnBuilder, _a281, "MySqlEnumObjectColumnBuilder");
    MySqlEnumObjectColumn = class extends (_b204 = MySqlColumn, _a282 = entityKind, _b204) {
      constructor() {
        super(...arguments);
        __publicField(this, "enumValues", this.config.enumValues);
      }
      getSQLType() {
        return `enum(${this.enumValues.map((value) => `'${value}'`).join(",")})`;
      }
    };
    __publicField(MySqlEnumObjectColumn, _a282, "MySqlEnumObjectColumn");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/float.js
function float(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlFloatBuilder(name2, config);
}
var _a283, _b205, MySqlFloatBuilder, _a284, _b206, MySqlFloat;
var init_float = __esm({
  "../drizzle-orm/dist/mysql-core/columns/float.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlFloatBuilder = class extends (_b205 = MySqlColumnBuilderWithAutoIncrement, _a283 = entityKind, _b205) {
      constructor(name2, config) {
        super(name2, "number", "MySqlFloat");
        this.config.precision = config?.precision;
        this.config.scale = config?.scale;
        this.config.unsigned = config?.unsigned;
      }
      /** @internal */
      build(table6) {
        return new MySqlFloat(table6, this.config);
      }
    };
    __publicField(MySqlFloatBuilder, _a283, "MySqlFloatBuilder");
    MySqlFloat = class extends (_b206 = MySqlColumnWithAutoIncrement, _a284 = entityKind, _b206) {
      constructor() {
        super(...arguments);
        __publicField(this, "precision", this.config.precision);
        __publicField(this, "scale", this.config.scale);
        __publicField(this, "unsigned", this.config.unsigned);
      }
      getSQLType() {
        let type = "";
        if (this.precision !== void 0 && this.scale !== void 0) {
          type += `float(${this.precision},${this.scale})`;
        } else if (this.precision === void 0) {
          type += "float";
        } else {
          type += `float(${this.precision})`;
        }
        return this.unsigned ? `${type} unsigned` : type;
      }
    };
    __publicField(MySqlFloat, _a284, "MySqlFloat");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/int.js
function int(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlIntBuilder(name2, config);
}
var _a285, _b207, MySqlIntBuilder, _a286, _b208, MySqlInt;
var init_int = __esm({
  "../drizzle-orm/dist/mysql-core/columns/int.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlIntBuilder = class extends (_b207 = MySqlColumnBuilderWithAutoIncrement, _a285 = entityKind, _b207) {
      constructor(name2, config) {
        super(name2, "number", "MySqlInt");
        this.config.unsigned = config ? config.unsigned : false;
      }
      /** @internal */
      build(table6) {
        return new MySqlInt(table6, this.config);
      }
    };
    __publicField(MySqlIntBuilder, _a285, "MySqlIntBuilder");
    MySqlInt = class extends (_b208 = MySqlColumnWithAutoIncrement, _a286 = entityKind, _b208) {
      getSQLType() {
        return `int${this.config.unsigned ? " unsigned" : ""}`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number(value);
        }
        return value;
      }
    };
    __publicField(MySqlInt, _a286, "MySqlInt");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/json.js
function json2(name2) {
  return new MySqlJsonBuilder(name2 ?? "");
}
var _a287, _b209, MySqlJsonBuilder, _a288, _b210, MySqlJson;
var init_json2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/json.js"() {
    "use strict";
    init_entity();
    init_common4();
    MySqlJsonBuilder = class extends (_b209 = MySqlColumnBuilder, _a287 = entityKind, _b209) {
      constructor(name2) {
        super(name2, "json", "MySqlJson");
      }
      /** @internal */
      build(table6) {
        return new MySqlJson(table6, this.config);
      }
    };
    __publicField(MySqlJsonBuilder, _a287, "MySqlJsonBuilder");
    MySqlJson = class extends (_b210 = MySqlColumn, _a288 = entityKind, _b210) {
      getSQLType() {
        return "json";
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
    };
    __publicField(MySqlJson, _a288, "MySqlJson");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/mediumint.js
function mediumint(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlMediumIntBuilder(name2, config);
}
var _a289, _b211, MySqlMediumIntBuilder, _a290, _b212, MySqlMediumInt;
var init_mediumint = __esm({
  "../drizzle-orm/dist/mysql-core/columns/mediumint.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlMediumIntBuilder = class extends (_b211 = MySqlColumnBuilderWithAutoIncrement, _a289 = entityKind, _b211) {
      constructor(name2, config) {
        super(name2, "number", "MySqlMediumInt");
        this.config.unsigned = config ? config.unsigned : false;
      }
      /** @internal */
      build(table6) {
        return new MySqlMediumInt(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlMediumIntBuilder, _a289, "MySqlMediumIntBuilder");
    MySqlMediumInt = class extends (_b212 = MySqlColumnWithAutoIncrement, _a290 = entityKind, _b212) {
      getSQLType() {
        return `mediumint${this.config.unsigned ? " unsigned" : ""}`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number(value);
        }
        return value;
      }
    };
    __publicField(MySqlMediumInt, _a290, "MySqlMediumInt");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/real.js
function real3(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlRealBuilder(name2, config);
}
var _a291, _b213, MySqlRealBuilder, _a292, _b214, MySqlReal;
var init_real3 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/real.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlRealBuilder = class extends (_b213 = MySqlColumnBuilderWithAutoIncrement, _a291 = entityKind, _b213) {
      constructor(name2, config) {
        super(name2, "number", "MySqlReal");
        this.config.precision = config?.precision;
        this.config.scale = config?.scale;
      }
      /** @internal */
      build(table6) {
        return new MySqlReal(table6, this.config);
      }
    };
    __publicField(MySqlRealBuilder, _a291, "MySqlRealBuilder");
    MySqlReal = class extends (_b214 = MySqlColumnWithAutoIncrement, _a292 = entityKind, _b214) {
      constructor() {
        super(...arguments);
        __publicField(this, "precision", this.config.precision);
        __publicField(this, "scale", this.config.scale);
      }
      getSQLType() {
        if (this.precision !== void 0 && this.scale !== void 0) {
          return `real(${this.precision}, ${this.scale})`;
        } else if (this.precision === void 0) {
          return "real";
        } else {
          return `real(${this.precision})`;
        }
      }
    };
    __publicField(MySqlReal, _a292, "MySqlReal");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/serial.js
function serial2(name2) {
  return new MySqlSerialBuilder(name2 ?? "");
}
var _a293, _b215, MySqlSerialBuilder, _a294, _b216, MySqlSerial;
var init_serial2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/serial.js"() {
    "use strict";
    init_entity();
    init_common4();
    MySqlSerialBuilder = class extends (_b215 = MySqlColumnBuilderWithAutoIncrement, _a293 = entityKind, _b215) {
      constructor(name2) {
        super(name2, "number", "MySqlSerial");
        this.config.hasDefault = true;
        this.config.autoIncrement = true;
      }
      /** @internal */
      build(table6) {
        return new MySqlSerial(table6, this.config);
      }
    };
    __publicField(MySqlSerialBuilder, _a293, "MySqlSerialBuilder");
    MySqlSerial = class extends (_b216 = MySqlColumnWithAutoIncrement, _a294 = entityKind, _b216) {
      getSQLType() {
        return "serial";
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number(value);
        }
        return value;
      }
    };
    __publicField(MySqlSerial, _a294, "MySqlSerial");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/smallint.js
function smallint2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlSmallIntBuilder(name2, config);
}
var _a295, _b217, MySqlSmallIntBuilder, _a296, _b218, MySqlSmallInt;
var init_smallint2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/smallint.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlSmallIntBuilder = class extends (_b217 = MySqlColumnBuilderWithAutoIncrement, _a295 = entityKind, _b217) {
      constructor(name2, config) {
        super(name2, "number", "MySqlSmallInt");
        this.config.unsigned = config ? config.unsigned : false;
      }
      /** @internal */
      build(table6) {
        return new MySqlSmallInt(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlSmallIntBuilder, _a295, "MySqlSmallIntBuilder");
    MySqlSmallInt = class extends (_b218 = MySqlColumnWithAutoIncrement, _a296 = entityKind, _b218) {
      getSQLType() {
        return `smallint${this.config.unsigned ? " unsigned" : ""}`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number(value);
        }
        return value;
      }
    };
    __publicField(MySqlSmallInt, _a296, "MySqlSmallInt");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/text.js
function text3(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlTextBuilder(name2, "text", config);
}
function tinytext(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlTextBuilder(name2, "tinytext", config);
}
function mediumtext(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlTextBuilder(name2, "mediumtext", config);
}
function longtext(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlTextBuilder(name2, "longtext", config);
}
var _a297, _b219, MySqlTextBuilder, _a298, _b220, MySqlText;
var init_text3 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/text.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlTextBuilder = class extends (_b219 = MySqlColumnBuilder, _a297 = entityKind, _b219) {
      constructor(name2, textType, config) {
        super(name2, "string", "MySqlText");
        this.config.textType = textType;
        this.config.enumValues = config.enum;
      }
      /** @internal */
      build(table6) {
        return new MySqlText(table6, this.config);
      }
    };
    __publicField(MySqlTextBuilder, _a297, "MySqlTextBuilder");
    MySqlText = class extends (_b220 = MySqlColumn, _a298 = entityKind, _b220) {
      constructor() {
        super(...arguments);
        __publicField(this, "textType", this.config.textType);
        __publicField(this, "enumValues", this.config.enumValues);
      }
      getSQLType() {
        return this.textType;
      }
    };
    __publicField(MySqlText, _a298, "MySqlText");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/time.js
function time2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlTimeBuilder(name2, config);
}
var _a299, _b221, MySqlTimeBuilder, _a300, _b222, MySqlTime;
var init_time2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/time.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlTimeBuilder = class extends (_b221 = MySqlColumnBuilder, _a299 = entityKind, _b221) {
      constructor(name2, config) {
        super(name2, "string", "MySqlTime");
        this.config.fsp = config?.fsp;
      }
      /** @internal */
      build(table6) {
        return new MySqlTime(table6, this.config);
      }
    };
    __publicField(MySqlTimeBuilder, _a299, "MySqlTimeBuilder");
    MySqlTime = class extends (_b222 = MySqlColumn, _a300 = entityKind, _b222) {
      constructor() {
        super(...arguments);
        __publicField(this, "fsp", this.config.fsp);
      }
      getSQLType() {
        const precision = this.fsp === void 0 ? "" : `(${this.fsp})`;
        return `time${precision}`;
      }
    };
    __publicField(MySqlTime, _a300, "MySqlTime");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/date.common.js
var _a301, _b223, MySqlDateColumnBaseBuilder, _a302, _b224, MySqlDateBaseColumn;
var init_date_common2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/date.common.js"() {
    "use strict";
    init_entity();
    init_sql();
    init_common4();
    MySqlDateColumnBaseBuilder = class extends (_b223 = MySqlColumnBuilder, _a301 = entityKind, _b223) {
      defaultNow() {
        return this.default(sql`(now())`);
      }
      // "on update now" also adds an implicit default value to the column - https://dev.mysql.com/doc/refman/8.0/en/timestamp-initialization.html
      onUpdateNow() {
        this.config.hasOnUpdateNow = true;
        this.config.hasDefault = true;
        return this;
      }
    };
    __publicField(MySqlDateColumnBaseBuilder, _a301, "MySqlDateColumnBuilder");
    MySqlDateBaseColumn = class extends (_b224 = MySqlColumn, _a302 = entityKind, _b224) {
      constructor() {
        super(...arguments);
        __publicField(this, "hasOnUpdateNow", this.config.hasOnUpdateNow);
      }
    };
    __publicField(MySqlDateBaseColumn, _a302, "MySqlDateColumn");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/timestamp.js
function timestamp2(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config?.mode === "string") {
    return new MySqlTimestampStringBuilder(name2, config);
  }
  return new MySqlTimestampBuilder(name2, config);
}
var _a303, _b225, MySqlTimestampBuilder, _a304, _b226, MySqlTimestamp, _a305, _b227, MySqlTimestampStringBuilder, _a306, _b228, MySqlTimestampString;
var init_timestamp2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/timestamp.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_date_common2();
    MySqlTimestampBuilder = class extends (_b225 = MySqlDateColumnBaseBuilder, _a303 = entityKind, _b225) {
      constructor(name2, config) {
        super(name2, "date", "MySqlTimestamp");
        this.config.fsp = config?.fsp;
      }
      /** @internal */
      build(table6) {
        return new MySqlTimestamp(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlTimestampBuilder, _a303, "MySqlTimestampBuilder");
    MySqlTimestamp = class extends (_b226 = MySqlDateBaseColumn, _a304 = entityKind, _b226) {
      constructor() {
        super(...arguments);
        __publicField(this, "fsp", this.config.fsp);
      }
      getSQLType() {
        const precision = this.fsp === void 0 ? "" : `(${this.fsp})`;
        return `timestamp${precision}`;
      }
      mapFromDriverValue(value) {
        return /* @__PURE__ */ new Date(value + "+0000");
      }
      mapToDriverValue(value) {
        return value.toISOString().slice(0, -1).replace("T", " ");
      }
    };
    __publicField(MySqlTimestamp, _a304, "MySqlTimestamp");
    MySqlTimestampStringBuilder = class extends (_b227 = MySqlDateColumnBaseBuilder, _a305 = entityKind, _b227) {
      constructor(name2, config) {
        super(name2, "string", "MySqlTimestampString");
        this.config.fsp = config?.fsp;
      }
      /** @internal */
      build(table6) {
        return new MySqlTimestampString(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlTimestampStringBuilder, _a305, "MySqlTimestampStringBuilder");
    MySqlTimestampString = class extends (_b228 = MySqlDateBaseColumn, _a306 = entityKind, _b228) {
      constructor() {
        super(...arguments);
        __publicField(this, "fsp", this.config.fsp);
      }
      getSQLType() {
        const precision = this.fsp === void 0 ? "" : `(${this.fsp})`;
        return `timestamp${precision}`;
      }
    };
    __publicField(MySqlTimestampString, _a306, "MySqlTimestampString");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/tinyint.js
function tinyint(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlTinyIntBuilder(name2, config);
}
var _a307, _b229, MySqlTinyIntBuilder, _a308, _b230, MySqlTinyInt;
var init_tinyint = __esm({
  "../drizzle-orm/dist/mysql-core/columns/tinyint.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlTinyIntBuilder = class extends (_b229 = MySqlColumnBuilderWithAutoIncrement, _a307 = entityKind, _b229) {
      constructor(name2, config) {
        super(name2, "number", "MySqlTinyInt");
        this.config.unsigned = config ? config.unsigned : false;
      }
      /** @internal */
      build(table6) {
        return new MySqlTinyInt(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlTinyIntBuilder, _a307, "MySqlTinyIntBuilder");
    MySqlTinyInt = class extends (_b230 = MySqlColumnWithAutoIncrement, _a308 = entityKind, _b230) {
      getSQLType() {
        return `tinyint${this.config.unsigned ? " unsigned" : ""}`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number(value);
        }
        return value;
      }
    };
    __publicField(MySqlTinyInt, _a308, "MySqlTinyInt");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/varbinary.js
function varbinary(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlVarBinaryBuilder(name2, config);
}
var _a309, _b231, MySqlVarBinaryBuilder, _a310, _b232, MySqlVarBinary;
var init_varbinary = __esm({
  "../drizzle-orm/dist/mysql-core/columns/varbinary.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlVarBinaryBuilder = class extends (_b231 = MySqlColumnBuilder, _a309 = entityKind, _b231) {
      /** @internal */
      constructor(name2, config) {
        super(name2, "string", "MySqlVarBinary");
        this.config.length = config?.length;
      }
      /** @internal */
      build(table6) {
        return new MySqlVarBinary(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlVarBinaryBuilder, _a309, "MySqlVarBinaryBuilder");
    MySqlVarBinary = class extends (_b232 = MySqlColumn, _a310 = entityKind, _b232) {
      constructor() {
        super(...arguments);
        __publicField(this, "length", this.config.length);
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") return value;
        if (Buffer.isBuffer(value)) return value.toString();
        const str = [];
        for (const v of value) {
          str.push(v === 49 ? "1" : "0");
        }
        return str.join("");
      }
      getSQLType() {
        return this.length === void 0 ? `varbinary` : `varbinary(${this.length})`;
      }
    };
    __publicField(MySqlVarBinary, _a310, "MySqlVarBinary");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/varchar.js
function varchar2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new MySqlVarCharBuilder(name2, config);
}
var _a311, _b233, MySqlVarCharBuilder, _a312, _b234, MySqlVarChar;
var init_varchar2 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/varchar.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common4();
    MySqlVarCharBuilder = class extends (_b233 = MySqlColumnBuilder, _a311 = entityKind, _b233) {
      /** @internal */
      constructor(name2, config) {
        super(name2, "string", "MySqlVarChar");
        this.config.length = config.length;
        this.config.enum = config.enum;
      }
      /** @internal */
      build(table6) {
        return new MySqlVarChar(
          table6,
          this.config
        );
      }
    };
    __publicField(MySqlVarCharBuilder, _a311, "MySqlVarCharBuilder");
    MySqlVarChar = class extends (_b234 = MySqlColumn, _a312 = entityKind, _b234) {
      constructor() {
        super(...arguments);
        __publicField(this, "length", this.config.length);
        __publicField(this, "enumValues", this.config.enum);
      }
      getSQLType() {
        return this.length === void 0 ? `varchar` : `varchar(${this.length})`;
      }
    };
    __publicField(MySqlVarChar, _a312, "MySqlVarChar");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/year.js
function year(name2) {
  return new MySqlYearBuilder(name2 ?? "");
}
var _a313, _b235, MySqlYearBuilder, _a314, _b236, MySqlYear;
var init_year = __esm({
  "../drizzle-orm/dist/mysql-core/columns/year.js"() {
    "use strict";
    init_entity();
    init_common4();
    MySqlYearBuilder = class extends (_b235 = MySqlColumnBuilder, _a313 = entityKind, _b235) {
      constructor(name2) {
        super(name2, "number", "MySqlYear");
      }
      /** @internal */
      build(table6) {
        return new MySqlYear(table6, this.config);
      }
    };
    __publicField(MySqlYearBuilder, _a313, "MySqlYearBuilder");
    MySqlYear = class extends (_b236 = MySqlColumn, _a314 = entityKind, _b236) {
      getSQLType() {
        return `year`;
      }
    };
    __publicField(MySqlYear, _a314, "MySqlYear");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/index.js
var init_columns3 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/index.js"() {
    "use strict";
    init_bigint2();
    init_binary();
    init_boolean2();
    init_char2();
    init_common4();
    init_custom3();
    init_date2();
    init_datetime();
    init_decimal();
    init_double();
    init_enum2();
    init_float();
    init_int();
    init_json2();
    init_mediumint();
    init_real3();
    init_serial2();
    init_smallint2();
    init_text3();
    init_time2();
    init_timestamp2();
    init_tinyint();
    init_varbinary();
    init_varchar2();
    init_year();
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/count.js
var _a315, _b237, _c9, _MySqlCountBuilder, MySqlCountBuilder;
var init_count3 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/count.js"() {
    "use strict";
    init_entity();
    init_sql();
    _MySqlCountBuilder = class _MySqlCountBuilder extends (_c9 = SQL, _b237 = entityKind, _a315 = Symbol.toStringTag, _c9) {
      constructor(params) {
        super(_MySqlCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
        __publicField(this, "sql");
        __publicField(this, _a315, "MySqlCountBuilder");
        __publicField(this, "session");
        this.params = params;
        this.mapWith(Number);
        this.session = params.session;
        this.sql = _MySqlCountBuilder.buildCount(
          params.source,
          params.filters
        );
      }
      static buildEmbeddedCount(source, filters) {
        return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
      }
      static buildCount(source, filters) {
        return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters}`;
      }
      then(onfulfilled, onrejected) {
        return Promise.resolve(this.session.count(this.sql)).then(
          onfulfilled,
          onrejected
        );
      }
      catch(onRejected) {
        return this.then(void 0, onRejected);
      }
      finally(onFinally) {
        return this.then(
          (value) => {
            onFinally?.();
            return value;
          },
          (reason) => {
            onFinally?.();
            throw reason;
          }
        );
      }
    };
    __publicField(_MySqlCountBuilder, _b237, "MySqlCountBuilder");
    MySqlCountBuilder = _MySqlCountBuilder;
  }
});

// ../drizzle-orm/dist/mysql-core/indexes.js
var _a316, IndexBuilderOn3, _a317, IndexBuilder3, _a318, Index5;
var init_indexes3 = __esm({
  "../drizzle-orm/dist/mysql-core/indexes.js"() {
    "use strict";
    init_entity();
    _a316 = entityKind;
    IndexBuilderOn3 = class {
      constructor(name2, unique) {
        this.name = name2;
        this.unique = unique;
      }
      on(...columns) {
        return new IndexBuilder3(this.name, columns, this.unique);
      }
    };
    __publicField(IndexBuilderOn3, _a316, "MySqlIndexBuilderOn");
    _a317 = entityKind;
    IndexBuilder3 = class {
      constructor(name2, columns, unique) {
        /** @internal */
        __publicField(this, "config");
        this.config = {
          name: name2,
          columns,
          unique
        };
      }
      using(using) {
        this.config.using = using;
        return this;
      }
      algorythm(algorythm) {
        this.config.algorythm = algorythm;
        return this;
      }
      lock(lock) {
        this.config.lock = lock;
        return this;
      }
      /** @internal */
      build(table6) {
        return new Index5(this.config, table6);
      }
    };
    __publicField(IndexBuilder3, _a317, "MySqlIndexBuilder");
    _a318 = entityKind;
    Index5 = class {
      constructor(config, table6) {
        __publicField(this, "config");
        this.config = { ...config, table: table6 };
      }
    };
    __publicField(Index5, _a318, "MySqlIndex");
  }
});

// ../drizzle-orm/dist/mysql-core/columns/all.js
function getMySqlColumnBuilders() {
  return {
    bigint: bigint2,
    binary,
    boolean: boolean2,
    char: char2,
    customType: customType3,
    date: date2,
    datetime,
    decimal,
    double,
    mysqlEnum,
    float,
    int,
    json: json2,
    mediumint,
    real: real3,
    serial: serial2,
    smallint: smallint2,
    text: text3,
    time: time2,
    timestamp: timestamp2,
    tinyint,
    varbinary,
    varchar: varchar2,
    year,
    longtext,
    mediumtext,
    tinytext
  };
}
var init_all3 = __esm({
  "../drizzle-orm/dist/mysql-core/columns/all.js"() {
    "use strict";
    init_bigint2();
    init_binary();
    init_boolean2();
    init_char2();
    init_custom3();
    init_date2();
    init_datetime();
    init_decimal();
    init_double();
    init_enum2();
    init_float();
    init_int();
    init_json2();
    init_mediumint();
    init_real3();
    init_serial2();
    init_smallint2();
    init_text3();
    init_time2();
    init_timestamp2();
    init_tinyint();
    init_varbinary();
    init_varchar2();
    init_year();
  }
});

// ../drizzle-orm/dist/mysql-core/table.js
function mysqlTableWithSchema(name2, columns, extraConfig, schema5, baseName = name2) {
  const rawTable = new MySqlTable(name2, schema5, baseName);
  const parsedColumns = typeof columns === "function" ? columns(getMySqlColumnBuilders()) : columns;
  const builtColumns = Object.fromEntries(
    Object.entries(parsedColumns).map(([name22, colBuilderBase]) => {
      const colBuilder = colBuilderBase;
      colBuilder.setName(name22);
      const column6 = colBuilder.build(rawTable);
      rawTable[InlineForeignKeys3].push(...colBuilder.buildForeignKeys(column6, rawTable));
      return [name22, column6];
    })
  );
  const table6 = Object.assign(rawTable, builtColumns);
  table6[Table2.Symbol.Columns] = builtColumns;
  table6[Table2.Symbol.ExtraConfigColumns] = builtColumns;
  if (extraConfig) {
    table6[MySqlTable.Symbol.ExtraConfigBuilder] = extraConfig;
  }
  return table6;
}
var InlineForeignKeys3, _a319, _b238, _c10, _d4, _e4, MySqlTable, mysqlTable;
var init_table4 = __esm({
  "../drizzle-orm/dist/mysql-core/table.js"() {
    "use strict";
    init_entity();
    init_table();
    init_all3();
    InlineForeignKeys3 = Symbol.for("drizzle:MySqlInlineForeignKeys");
    MySqlTable = class extends (_e4 = Table2, _d4 = entityKind, _c10 = Table2.Symbol.Columns, _b238 = InlineForeignKeys3, _a319 = Table2.Symbol.ExtraConfigBuilder, _e4) {
      constructor() {
        super(...arguments);
        /** @internal */
        __publicField(this, _c10);
        /** @internal */
        __publicField(this, _b238, []);
        /** @internal */
        __publicField(this, _a319);
      }
    };
    __publicField(MySqlTable, _d4, "MySqlTable");
    /** @internal */
    __publicField(MySqlTable, "Symbol", Object.assign({}, Table2.Symbol, {
      InlineForeignKeys: InlineForeignKeys3
    }));
    mysqlTable = (name2, columns, extraConfig) => {
      return mysqlTableWithSchema(name2, columns, extraConfig, void 0, name2);
    };
  }
});

// ../drizzle-orm/dist/mysql-core/primary-keys.js
var _a320, PrimaryKeyBuilder3, _a321, PrimaryKey3;
var init_primary_keys3 = __esm({
  "../drizzle-orm/dist/mysql-core/primary-keys.js"() {
    "use strict";
    init_entity();
    init_table4();
    _a320 = entityKind;
    PrimaryKeyBuilder3 = class {
      constructor(columns, name2) {
        /** @internal */
        __publicField(this, "columns");
        /** @internal */
        __publicField(this, "name");
        this.columns = columns;
        this.name = name2;
      }
      /** @internal */
      build(table6) {
        return new PrimaryKey3(table6, this.columns, this.name);
      }
    };
    __publicField(PrimaryKeyBuilder3, _a320, "MySqlPrimaryKeyBuilder");
    _a321 = entityKind;
    PrimaryKey3 = class {
      constructor(table6, columns, name2) {
        __publicField(this, "columns");
        __publicField(this, "name");
        this.table = table6;
        this.columns = columns;
        this.name = name2;
      }
      getName() {
        return this.name ?? `${this.table[MySqlTable.Symbol.Name]}_${this.columns.map((column6) => column6.name).join("_")}_pk`;
      }
    };
    __publicField(PrimaryKey3, _a321, "MySqlPrimaryKey");
  }
});

// ../drizzle-orm/dist/mysql-core/view-common.js
var MySqlViewConfig;
var init_view_common3 = __esm({
  "../drizzle-orm/dist/mysql-core/view-common.js"() {
    "use strict";
    MySqlViewConfig = Symbol.for("drizzle:MySqlViewConfig");
  }
});

// ../drizzle-orm/dist/mysql-core/utils.js
function extractUsedTable3(table6) {
  if (is(table6, MySqlTable)) {
    return [`${table6[Table2.Symbol.BaseName]}`];
  }
  if (is(table6, Subquery)) {
    return table6._.usedTables ?? [];
  }
  if (is(table6, SQL)) {
    return table6.usedTables ?? [];
  }
  return [];
}
function getTableConfig3(table6) {
  const columns = Object.values(table6[MySqlTable.Symbol.Columns]);
  const indexes = [];
  const checks = [];
  const primaryKeys = [];
  const uniqueConstraints = [];
  const foreignKeys = Object.values(table6[MySqlTable.Symbol.InlineForeignKeys]);
  const name2 = table6[Table2.Symbol.Name];
  const schema5 = table6[Table2.Symbol.Schema];
  const baseName = table6[Table2.Symbol.BaseName];
  const extraConfigBuilder = table6[MySqlTable.Symbol.ExtraConfigBuilder];
  if (extraConfigBuilder !== void 0) {
    const extraConfig = extraConfigBuilder(table6[MySqlTable.Symbol.Columns]);
    const extraValues = Array.isArray(extraConfig) ? extraConfig.flat(1) : Object.values(extraConfig);
    for (const builder of Object.values(extraValues)) {
      if (is(builder, IndexBuilder3)) {
        indexes.push(builder.build(table6));
      } else if (is(builder, CheckBuilder3)) {
        checks.push(builder.build(table6));
      } else if (is(builder, UniqueConstraintBuilder3)) {
        uniqueConstraints.push(builder.build(table6));
      } else if (is(builder, PrimaryKeyBuilder3)) {
        primaryKeys.push(builder.build(table6));
      } else if (is(builder, ForeignKeyBuilder3)) {
        foreignKeys.push(builder.build(table6));
      }
    }
  }
  return {
    columns,
    indexes,
    foreignKeys,
    checks,
    primaryKeys,
    uniqueConstraints,
    name: name2,
    schema: schema5,
    baseName
  };
}
function getViewConfig3(view5) {
  return {
    ...view5[ViewBaseConfig],
    ...view5[MySqlViewConfig]
  };
}
function convertIndexToString(indexes) {
  return indexes.map((idx) => {
    return typeof idx === "object" ? idx.config.name : idx;
  });
}
function toArray(value) {
  return Array.isArray(value) ? value : [value];
}
var init_utils8 = __esm({
  "../drizzle-orm/dist/mysql-core/utils.js"() {
    "use strict";
    init_entity();
    init_dist();
    init_subquery();
    init_table();
    init_view_common();
    init_checks3();
    init_foreign_keys3();
    init_indexes3();
    init_primary_keys3();
    init_table4();
    init_unique_constraint3();
    init_view_common3();
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/delete.js
var _a322, _b239, MySqlDeleteBase;
var init_delete3 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/delete.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_selection_proxy();
    init_table();
    init_utils8();
    MySqlDeleteBase = class extends (_b239 = QueryPromise, _a322 = entityKind, _b239) {
      constructor(table6, session, dialect6, withList) {
        super();
        __publicField(this, "config");
        __publicField(this, "execute", (placeholderValues) => {
          return this.prepare().execute(placeholderValues);
        });
        __publicField(this, "createIterator", () => {
          const self2 = this;
          return async function* (placeholderValues) {
            yield* self2.prepare().iterator(placeholderValues);
          };
        });
        __publicField(this, "iterator", this.createIterator());
        this.table = table6;
        this.session = session;
        this.dialect = dialect6;
        this.config = { table: table6, withList };
      }
      /**
       * Adds a `where` clause to the query.
       *
       * Calling this method will delete only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/delete}
       *
       * @param where the `where` clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be deleted.
       *
       * ```ts
       * // Delete all cars with green color
       * db.delete(cars).where(eq(cars.color, 'green'));
       * // or
       * db.delete(cars).where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Delete all BMW cars with a green color
       * db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Delete all cars with the green or blue color
       * db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        this.config.where = where;
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.table[Table2.Symbol.Columns],
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          this.config.orderBy = orderByArray;
        } else {
          const orderByArray = columns;
          this.config.orderBy = orderByArray;
        }
        return this;
      }
      limit(limit) {
        this.config.limit = limit;
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildDeleteQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      prepare() {
        return this.session.prepareQuery(
          this.dialect.sqlToQuery(this.getSQL()),
          this.config.returning,
          void 0,
          void 0,
          void 0,
          {
            type: "delete",
            tables: extractUsedTable3(this.config.table)
          }
        );
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(MySqlDeleteBase, _a322, "MySqlDelete");
  }
});

// ../drizzle-orm/dist/mysql-core/view-base.js
var _a323, _b240, MySqlViewBase;
var init_view_base3 = __esm({
  "../drizzle-orm/dist/mysql-core/view-base.js"() {
    "use strict";
    init_entity();
    init_sql();
    MySqlViewBase = class extends (_b240 = View3, _a323 = entityKind, _b240) {
    };
    __publicField(MySqlViewBase, _a323, "MySqlViewBase");
  }
});

// ../drizzle-orm/dist/mysql-core/dialect.js
var _a324, MySqlDialect;
var init_dialect3 = __esm({
  "../drizzle-orm/dist/mysql-core/dialect.js"() {
    "use strict";
    init_alias();
    init_casing();
    init_column();
    init_entity();
    init_errors2();
    init_relations();
    init_expressions();
    init_sql();
    init_subquery();
    init_table();
    init_utils2();
    init_view_common();
    init_common4();
    init_table4();
    init_view_base3();
    _a324 = entityKind;
    MySqlDialect = class {
      constructor(config) {
        /** @internal */
        __publicField(this, "casing");
        this.casing = new CasingCache(config?.casing);
      }
      async migrate(migrations, session, config) {
        const migrationsTable = config.migrationsTable ?? "__drizzle_migrations";
        const migrationTableCreate = sql`
			create table if not exists ${sql.identifier(migrationsTable)} (
				id serial primary key,
				hash text not null,
				created_at bigint
			)
		`;
        await session.execute(migrationTableCreate);
        const dbMigrations = await session.all(
          sql`select id, hash, created_at from ${sql.identifier(migrationsTable)} order by created_at desc limit 1`
        );
        const lastDbMigration = dbMigrations[0];
        await session.transaction(async (tx) => {
          for (const migration of migrations) {
            if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) {
              for (const stmt of migration.sql) {
                await tx.execute(sql.raw(stmt));
              }
              await tx.execute(
                sql`insert into ${sql.identifier(migrationsTable)} (\`hash\`, \`created_at\`) values(${migration.hash}, ${migration.folderMillis})`
              );
            }
          }
        });
      }
      escapeName(name2) {
        return `\`${name2}\``;
      }
      escapeParam(_num) {
        return `?`;
      }
      escapeString(str) {
        return `'${str.replace(/'/g, "''")}'`;
      }
      buildWithCTE(queries) {
        if (!queries?.length) return void 0;
        const withSqlChunks = [sql`with `];
        for (const [i, w] of queries.entries()) {
          withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
          if (i < queries.length - 1) {
            withSqlChunks.push(sql`, `);
          }
        }
        withSqlChunks.push(sql` `);
        return sql.join(withSqlChunks);
      }
      buildDeleteQuery({ table: table6, where, returning, withList, limit, orderBy }) {
        const withSql = this.buildWithCTE(withList);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const whereSql = where ? sql` where ${where}` : void 0;
        const orderBySql = this.buildOrderBy(orderBy);
        const limitSql = this.buildLimit(limit);
        return sql`${withSql}delete from ${table6}${whereSql}${orderBySql}${limitSql}${returningSql}`;
      }
      buildUpdateSet(table6, set) {
        const tableColumns = table6[Table2.Symbol.Columns];
        const columnNames = Object.keys(tableColumns).filter(
          (colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0
        );
        const setSize = columnNames.length;
        return sql.join(columnNames.flatMap((colName, i) => {
          const col = tableColumns[colName];
          const value = set[colName] ?? sql.param(col.onUpdateFn(), col);
          const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
          if (i < setSize - 1) {
            return [res, sql.raw(", ")];
          }
          return [res];
        }));
      }
      buildUpdateQuery({ table: table6, set, where, returning, withList, limit, orderBy }) {
        const withSql = this.buildWithCTE(withList);
        const setSql = this.buildUpdateSet(table6, set);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const whereSql = where ? sql` where ${where}` : void 0;
        const orderBySql = this.buildOrderBy(orderBy);
        const limitSql = this.buildLimit(limit);
        return sql`${withSql}update ${table6} set ${setSql}${whereSql}${orderBySql}${limitSql}${returningSql}`;
      }
      /**
       * Builds selection SQL with provided fields/expressions
       *
       * Examples:
       *
       * `select <selection> from`
       *
       * `insert ... returning <selection>`
       *
       * If `isSingleTable` is true, then columns won't be prefixed with table name
       */
      buildSelection(fields, { isSingleTable = false } = {}) {
        const columnsLen = fields.length;
        const chunks = fields.flatMap(({ field }, i) => {
          const chunk = [];
          if (is(field, SQL.Aliased) && field.isSelectionField) {
            chunk.push(sql.identifier(field.fieldAlias));
          } else if (is(field, SQL.Aliased) || is(field, SQL)) {
            const query = is(field, SQL.Aliased) ? field.sql : field;
            if (isSingleTable) {
              chunk.push(
                new SQL(
                  query.queryChunks.map((c) => {
                    if (is(c, MySqlColumn)) {
                      return sql.identifier(this.casing.getColumnCasing(c));
                    }
                    return c;
                  })
                )
              );
            } else {
              chunk.push(query);
            }
            if (is(field, SQL.Aliased)) {
              chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
            }
          } else if (is(field, Column2)) {
            if (isSingleTable) {
              chunk.push(sql.identifier(this.casing.getColumnCasing(field)));
            } else {
              chunk.push(field);
            }
          }
          if (i < columnsLen - 1) {
            chunk.push(sql`, `);
          }
          return chunk;
        });
        return sql.join(chunks);
      }
      buildLimit(limit) {
        return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
      }
      buildOrderBy(orderBy) {
        return orderBy && orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : void 0;
      }
      buildIndex({
        indexes,
        indexFor
      }) {
        return indexes && indexes.length > 0 ? sql` ${sql.raw(indexFor)} INDEX (${sql.raw(indexes.join(`, `))})` : void 0;
      }
      buildSelectQuery({
        withList,
        fields,
        fieldsFlat,
        where,
        having,
        table: table6,
        joins,
        orderBy,
        groupBy,
        limit,
        offset,
        lockingClause,
        distinct,
        setOperators,
        useIndex,
        forceIndex,
        ignoreIndex
      }) {
        const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
        for (const f of fieldsList) {
          if (is(f.field, Column2) && getTableName(f.field.table) !== (is(table6, Subquery) ? table6._.alias : is(table6, MySqlViewBase) ? table6[ViewBaseConfig].name : is(table6, SQL) ? void 0 : getTableName(table6)) && !((table22) => joins?.some(
            ({ alias }) => alias === (table22[Table2.Symbol.IsAlias] ? getTableName(table22) : table22[Table2.Symbol.BaseName])
          ))(f.field.table)) {
            const tableName = getTableName(f.field.table);
            throw new Error(
              `Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`
            );
          }
        }
        const isSingleTable = !joins || joins.length === 0;
        const withSql = this.buildWithCTE(withList);
        const distinctSql = distinct ? sql` distinct` : void 0;
        const selection = this.buildSelection(fieldsList, { isSingleTable });
        const tableSql = (() => {
          if (is(table6, Table2) && table6[Table2.Symbol.IsAlias]) {
            return sql`${sql`${sql.identifier(table6[Table2.Symbol.Schema] ?? "")}.`.if(table6[Table2.Symbol.Schema])}${sql.identifier(table6[Table2.Symbol.OriginalName])} ${sql.identifier(table6[Table2.Symbol.Name])}`;
          }
          return table6;
        })();
        const joinsArray = [];
        if (joins) {
          for (const [index6, joinMeta] of joins.entries()) {
            if (index6 === 0) {
              joinsArray.push(sql` `);
            }
            const table22 = joinMeta.table;
            const lateralSql = joinMeta.lateral ? sql` lateral` : void 0;
            const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0;
            if (is(table22, MySqlTable)) {
              const tableName = table22[MySqlTable.Symbol.Name];
              const tableSchema = table22[MySqlTable.Symbol.Schema];
              const origTableName = table22[MySqlTable.Symbol.OriginalName];
              const alias = tableName === origTableName ? void 0 : joinMeta.alias;
              const useIndexSql2 = this.buildIndex({ indexes: joinMeta.useIndex, indexFor: "USE" });
              const forceIndexSql2 = this.buildIndex({ indexes: joinMeta.forceIndex, indexFor: "FORCE" });
              const ignoreIndexSql2 = this.buildIndex({ indexes: joinMeta.ignoreIndex, indexFor: "IGNORE" });
              joinsArray.push(
                sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${useIndexSql2}${forceIndexSql2}${ignoreIndexSql2}${alias && sql` ${sql.identifier(alias)}`}${onSql}`
              );
            } else if (is(table22, View3)) {
              const viewName = table22[ViewBaseConfig].name;
              const viewSchema = table22[ViewBaseConfig].schema;
              const origViewName = table22[ViewBaseConfig].originalName;
              const alias = viewName === origViewName ? void 0 : joinMeta.alias;
              joinsArray.push(
                sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : void 0}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`
              );
            } else {
              joinsArray.push(
                sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table22}${onSql}`
              );
            }
            if (index6 < joins.length - 1) {
              joinsArray.push(sql` `);
            }
          }
        }
        const joinsSql = sql.join(joinsArray);
        const whereSql = where ? sql` where ${where}` : void 0;
        const havingSql = having ? sql` having ${having}` : void 0;
        const orderBySql = this.buildOrderBy(orderBy);
        const groupBySql = groupBy && groupBy.length > 0 ? sql` group by ${sql.join(groupBy, sql`, `)}` : void 0;
        const limitSql = this.buildLimit(limit);
        const offsetSql = offset ? sql` offset ${offset}` : void 0;
        const useIndexSql = this.buildIndex({ indexes: useIndex, indexFor: "USE" });
        const forceIndexSql = this.buildIndex({ indexes: forceIndex, indexFor: "FORCE" });
        const ignoreIndexSql = this.buildIndex({ indexes: ignoreIndex, indexFor: "IGNORE" });
        let lockingClausesSql;
        if (lockingClause) {
          const { config, strength } = lockingClause;
          lockingClausesSql = sql` for ${sql.raw(strength)}`;
          if (config.noWait) {
            lockingClausesSql.append(sql` nowait`);
          } else if (config.skipLocked) {
            lockingClausesSql.append(sql` skip locked`);
          }
        }
        const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${useIndexSql}${forceIndexSql}${ignoreIndexSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClausesSql}`;
        if (setOperators.length > 0) {
          return this.buildSetOperations(finalQuery, setOperators);
        }
        return finalQuery;
      }
      buildSetOperations(leftSelect, setOperators) {
        const [setOperator, ...rest] = setOperators;
        if (!setOperator) {
          throw new Error("Cannot pass undefined values to any set operator");
        }
        if (rest.length === 0) {
          return this.buildSetOperationQuery({ leftSelect, setOperator });
        }
        return this.buildSetOperations(
          this.buildSetOperationQuery({ leftSelect, setOperator }),
          rest
        );
      }
      buildSetOperationQuery({
        leftSelect,
        setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
      }) {
        const leftChunk = sql`(${leftSelect.getSQL()}) `;
        const rightChunk = sql`(${rightSelect.getSQL()})`;
        let orderBySql;
        if (orderBy && orderBy.length > 0) {
          const orderByValues = [];
          for (const orderByUnit of orderBy) {
            if (is(orderByUnit, MySqlColumn)) {
              orderByValues.push(sql.identifier(this.casing.getColumnCasing(orderByUnit)));
            } else if (is(orderByUnit, SQL)) {
              for (let i = 0; i < orderByUnit.queryChunks.length; i++) {
                const chunk = orderByUnit.queryChunks[i];
                if (is(chunk, MySqlColumn)) {
                  orderByUnit.queryChunks[i] = sql.identifier(this.casing.getColumnCasing(chunk));
                }
              }
              orderByValues.push(sql`${orderByUnit}`);
            } else {
              orderByValues.push(sql`${orderByUnit}`);
            }
          }
          orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `;
        }
        const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
        const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
        const offsetSql = offset ? sql` offset ${offset}` : void 0;
        return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
      }
      buildInsertQuery({ table: table6, values: valuesOrSelect, ignore, onConflict, select }) {
        const valuesSqlList = [];
        const columns = table6[Table2.Symbol.Columns];
        const colEntries = Object.entries(columns).filter(
          ([_2, col]) => !col.shouldDisableInsert()
        );
        const insertOrder = colEntries.map(([, column6]) => sql.identifier(this.casing.getColumnCasing(column6)));
        const generatedIdsResponse = [];
        if (select) {
          const select2 = valuesOrSelect;
          if (is(select2, SQL)) {
            valuesSqlList.push(select2);
          } else {
            valuesSqlList.push(select2.getSQL());
          }
        } else {
          const values = valuesOrSelect;
          valuesSqlList.push(sql.raw("values "));
          for (const [valueIndex, value] of values.entries()) {
            const generatedIds = {};
            const valueList = [];
            for (const [fieldName, col] of colEntries) {
              const colValue = value[fieldName];
              if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
                if (col.defaultFn !== void 0) {
                  const defaultFnResult = col.defaultFn();
                  generatedIds[fieldName] = defaultFnResult;
                  const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
                  valueList.push(defaultValue);
                } else if (!col.default && col.onUpdateFn !== void 0) {
                  const onUpdateFnResult = col.onUpdateFn();
                  const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
                  valueList.push(newValue);
                } else {
                  valueList.push(sql`default`);
                }
              } else {
                if (col.defaultFn && is(colValue, Param)) {
                  generatedIds[fieldName] = colValue.value;
                }
                valueList.push(colValue);
              }
            }
            generatedIdsResponse.push(generatedIds);
            valuesSqlList.push(valueList);
            if (valueIndex < values.length - 1) {
              valuesSqlList.push(sql`, `);
            }
          }
        }
        const valuesSql = sql.join(valuesSqlList);
        const ignoreSql = ignore ? sql` ignore` : void 0;
        const onConflictSql = onConflict ? sql` on duplicate key ${onConflict}` : void 0;
        return {
          sql: sql`insert${ignoreSql} into ${table6} ${insertOrder} ${valuesSql}${onConflictSql}`,
          generatedIds: generatedIdsResponse
        };
      }
      sqlToQuery(sql2, invokeSource) {
        return sql2.toQuery({
          casing: this.casing,
          escapeName: this.escapeName,
          escapeParam: this.escapeParam,
          escapeString: this.escapeString,
          invokeSource
        });
      }
      buildRelationalQuery({
        fullSchema,
        schema: schema5,
        tableNamesMap,
        table: table6,
        tableConfig,
        queryConfig: config,
        tableAlias,
        nestedQueryRelation,
        joinOn
      }) {
        let selection = [];
        let limit, offset, orderBy, where;
        const joins = [];
        if (config === true) {
          const selectionEntries = Object.entries(tableConfig.columns);
          selection = selectionEntries.map(([key, value]) => ({
            dbKey: value.name,
            tsKey: key,
            field: aliasedTableColumn(value, tableAlias),
            relationTableTsKey: void 0,
            isJson: false,
            selection: []
          }));
        } else {
          const aliasedColumns = Object.fromEntries(
            Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)])
          );
          if (config.where) {
            const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
            where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
          }
          const fieldsSelection = [];
          let selectedColumns = [];
          if (config.columns) {
            let isIncludeMode = false;
            for (const [field, value] of Object.entries(config.columns)) {
              if (value === void 0) {
                continue;
              }
              if (field in tableConfig.columns) {
                if (!isIncludeMode && value === true) {
                  isIncludeMode = true;
                }
                selectedColumns.push(field);
              }
            }
            if (selectedColumns.length > 0) {
              selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
            }
          } else {
            selectedColumns = Object.keys(tableConfig.columns);
          }
          for (const field of selectedColumns) {
            const column6 = tableConfig.columns[field];
            fieldsSelection.push({ tsKey: field, value: column6 });
          }
          let selectedRelations = [];
          if (config.with) {
            selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
          }
          let extras;
          if (config.extras) {
            extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
            for (const [tsKey, value] of Object.entries(extras)) {
              fieldsSelection.push({
                tsKey,
                value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
              });
            }
          }
          for (const { tsKey, value } of fieldsSelection) {
            selection.push({
              dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
              tsKey,
              field: is(value, Column2) ? aliasedTableColumn(value, tableAlias) : value,
              relationTableTsKey: void 0,
              isJson: false,
              selection: []
            });
          }
          let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
          if (!Array.isArray(orderByOrig)) {
            orderByOrig = [orderByOrig];
          }
          orderBy = orderByOrig.map((orderByValue) => {
            if (is(orderByValue, Column2)) {
              return aliasedTableColumn(orderByValue, tableAlias);
            }
            return mapColumnsInSQLToAlias(orderByValue, tableAlias);
          });
          limit = config.limit;
          offset = config.offset;
          for (const {
            tsKey: selectedRelationTsKey,
            queryConfig: selectedRelationConfigValue,
            relation
          } of selectedRelations) {
            const normalizedRelation = normalizeRelation(schema5, tableNamesMap, relation);
            const relationTableName = getTableUniqueName(relation.referencedTable);
            const relationTableTsName = tableNamesMap[relationTableName];
            const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
            const joinOn2 = and(
              ...normalizedRelation.fields.map(
                (field2, i) => eq(
                  aliasedTableColumn(normalizedRelation.references[i], relationTableAlias),
                  aliasedTableColumn(field2, tableAlias)
                )
              )
            );
            const builtRelation = this.buildRelationalQuery({
              fullSchema,
              schema: schema5,
              tableNamesMap,
              table: fullSchema[relationTableTsName],
              tableConfig: schema5[relationTableTsName],
              queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
              tableAlias: relationTableAlias,
              joinOn: joinOn2,
              nestedQueryRelation: relation
            });
            const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier("data")}`.as(selectedRelationTsKey);
            joins.push({
              on: sql`true`,
              table: new Subquery(builtRelation.sql, {}, relationTableAlias),
              alias: relationTableAlias,
              joinType: "left",
              lateral: true
            });
            selection.push({
              dbKey: selectedRelationTsKey,
              tsKey: selectedRelationTsKey,
              field,
              relationTableTsKey: relationTableTsName,
              isJson: true,
              selection: builtRelation.selection
            });
          }
        }
        if (selection.length === 0) {
          throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` });
        }
        let result;
        where = and(joinOn, where);
        if (nestedQueryRelation) {
          let field = sql`json_array(${sql.join(
            selection.map(
              ({ field: field2, tsKey, isJson }) => isJson ? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2
            ),
            sql`, `
          )})`;
          if (is(nestedQueryRelation, Many)) {
            field = sql`coalesce(json_arrayagg(${field}), json_array())`;
          }
          const nestedSelection = [{
            dbKey: "data",
            tsKey: "data",
            field: field.as("data"),
            isJson: true,
            relationTableTsKey: tableConfig.tsName,
            selection
          }];
          const needsSubquery = limit !== void 0 || offset !== void 0 || (orderBy?.length ?? 0) > 0;
          if (needsSubquery) {
            result = this.buildSelectQuery({
              table: aliasedTable(table6, tableAlias),
              fields: {},
              fieldsFlat: [
                {
                  path: [],
                  field: sql.raw("*")
                },
                ...(orderBy?.length ?? 0) > 0 ? [{
                  path: [],
                  field: sql`row_number() over (order by ${sql.join(orderBy, sql`, `)})`
                }] : []
              ],
              where,
              limit,
              offset,
              setOperators: []
            });
            where = void 0;
            limit = void 0;
            offset = void 0;
            orderBy = void 0;
          } else {
            result = aliasedTable(table6, tableAlias);
          }
          result = this.buildSelectQuery({
            table: is(result, MySqlTable) ? result : new Subquery(result, {}, tableAlias),
            fields: {},
            fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
              path: [],
              field: is(field2, Column2) ? aliasedTableColumn(field2, tableAlias) : field2
            })),
            joins,
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        } else {
          result = this.buildSelectQuery({
            table: aliasedTable(table6, tableAlias),
            fields: {},
            fieldsFlat: selection.map(({ field }) => ({
              path: [],
              field: is(field, Column2) ? aliasedTableColumn(field, tableAlias) : field
            })),
            joins,
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        }
        return {
          tableTsKey: tableConfig.tsName,
          sql: result,
          selection
        };
      }
      buildRelationalQueryWithoutLateralSubqueries({
        fullSchema,
        schema: schema5,
        tableNamesMap,
        table: table6,
        tableConfig,
        queryConfig: config,
        tableAlias,
        nestedQueryRelation,
        joinOn
      }) {
        let selection = [];
        let limit, offset, orderBy = [], where;
        if (config === true) {
          const selectionEntries = Object.entries(tableConfig.columns);
          selection = selectionEntries.map(([key, value]) => ({
            dbKey: value.name,
            tsKey: key,
            field: aliasedTableColumn(value, tableAlias),
            relationTableTsKey: void 0,
            isJson: false,
            selection: []
          }));
        } else {
          const aliasedColumns = Object.fromEntries(
            Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)])
          );
          if (config.where) {
            const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
            where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
          }
          const fieldsSelection = [];
          let selectedColumns = [];
          if (config.columns) {
            let isIncludeMode = false;
            for (const [field, value] of Object.entries(config.columns)) {
              if (value === void 0) {
                continue;
              }
              if (field in tableConfig.columns) {
                if (!isIncludeMode && value === true) {
                  isIncludeMode = true;
                }
                selectedColumns.push(field);
              }
            }
            if (selectedColumns.length > 0) {
              selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
            }
          } else {
            selectedColumns = Object.keys(tableConfig.columns);
          }
          for (const field of selectedColumns) {
            const column6 = tableConfig.columns[field];
            fieldsSelection.push({ tsKey: field, value: column6 });
          }
          let selectedRelations = [];
          if (config.with) {
            selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
          }
          let extras;
          if (config.extras) {
            extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
            for (const [tsKey, value] of Object.entries(extras)) {
              fieldsSelection.push({
                tsKey,
                value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
              });
            }
          }
          for (const { tsKey, value } of fieldsSelection) {
            selection.push({
              dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
              tsKey,
              field: is(value, Column2) ? aliasedTableColumn(value, tableAlias) : value,
              relationTableTsKey: void 0,
              isJson: false,
              selection: []
            });
          }
          let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
          if (!Array.isArray(orderByOrig)) {
            orderByOrig = [orderByOrig];
          }
          orderBy = orderByOrig.map((orderByValue) => {
            if (is(orderByValue, Column2)) {
              return aliasedTableColumn(orderByValue, tableAlias);
            }
            return mapColumnsInSQLToAlias(orderByValue, tableAlias);
          });
          limit = config.limit;
          offset = config.offset;
          for (const {
            tsKey: selectedRelationTsKey,
            queryConfig: selectedRelationConfigValue,
            relation
          } of selectedRelations) {
            const normalizedRelation = normalizeRelation(schema5, tableNamesMap, relation);
            const relationTableName = getTableUniqueName(relation.referencedTable);
            const relationTableTsName = tableNamesMap[relationTableName];
            const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
            const joinOn2 = and(
              ...normalizedRelation.fields.map(
                (field2, i) => eq(
                  aliasedTableColumn(normalizedRelation.references[i], relationTableAlias),
                  aliasedTableColumn(field2, tableAlias)
                )
              )
            );
            const builtRelation = this.buildRelationalQueryWithoutLateralSubqueries({
              fullSchema,
              schema: schema5,
              tableNamesMap,
              table: fullSchema[relationTableTsName],
              tableConfig: schema5[relationTableTsName],
              queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
              tableAlias: relationTableAlias,
              joinOn: joinOn2,
              nestedQueryRelation: relation
            });
            let fieldSql = sql`(${builtRelation.sql})`;
            if (is(relation, Many)) {
              fieldSql = sql`coalesce(${fieldSql}, json_array())`;
            }
            const field = fieldSql.as(selectedRelationTsKey);
            selection.push({
              dbKey: selectedRelationTsKey,
              tsKey: selectedRelationTsKey,
              field,
              relationTableTsKey: relationTableTsName,
              isJson: true,
              selection: builtRelation.selection
            });
          }
        }
        if (selection.length === 0) {
          throw new DrizzleError({
            message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`
          });
        }
        let result;
        where = and(joinOn, where);
        if (nestedQueryRelation) {
          let field = sql`json_array(${sql.join(
            selection.map(
              ({ field: field2 }) => is(field2, MySqlColumn) ? sql.identifier(this.casing.getColumnCasing(field2)) : is(field2, SQL.Aliased) ? field2.sql : field2
            ),
            sql`, `
          )})`;
          if (is(nestedQueryRelation, Many)) {
            field = sql`json_arrayagg(${field})`;
          }
          const nestedSelection = [{
            dbKey: "data",
            tsKey: "data",
            field,
            isJson: true,
            relationTableTsKey: tableConfig.tsName,
            selection
          }];
          const needsSubquery = limit !== void 0 || offset !== void 0 || orderBy.length > 0;
          if (needsSubquery) {
            result = this.buildSelectQuery({
              table: aliasedTable(table6, tableAlias),
              fields: {},
              fieldsFlat: [
                {
                  path: [],
                  field: sql.raw("*")
                },
                ...orderBy.length > 0 ? [{
                  path: [],
                  field: sql`row_number() over (order by ${sql.join(orderBy, sql`, `)})`
                }] : []
              ],
              where,
              limit,
              offset,
              setOperators: []
            });
            where = void 0;
            limit = void 0;
            offset = void 0;
            orderBy = void 0;
          } else {
            result = aliasedTable(table6, tableAlias);
          }
          result = this.buildSelectQuery({
            table: is(result, MySqlTable) ? result : new Subquery(result, {}, tableAlias),
            fields: {},
            fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
              path: [],
              field: is(field2, Column2) ? aliasedTableColumn(field2, tableAlias) : field2
            })),
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        } else {
          result = this.buildSelectQuery({
            table: aliasedTable(table6, tableAlias),
            fields: {},
            fieldsFlat: selection.map(({ field }) => ({
              path: [],
              field: is(field, Column2) ? aliasedTableColumn(field, tableAlias) : field
            })),
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        }
        return {
          tableTsKey: tableConfig.tsName,
          sql: result,
          selection
        };
      }
    };
    __publicField(MySqlDialect, _a324, "MySqlDialect");
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/select.js
function createSetOperator3(type, isAll) {
  return (leftSelect, rightSelect, ...restSelects) => {
    const setOperators = [rightSelect, ...restSelects].map((select) => ({
      type,
      isAll,
      rightSelect: select
    }));
    for (const setOperator of setOperators) {
      if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
        throw new Error(
          "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
        );
      }
    }
    return leftSelect.addSetOperators(setOperators);
  };
}
var _a325, MySqlSelectBuilder, _a326, _b241, MySqlSelectQueryBuilderBase, _a327, _b242, MySqlSelectBase, getMySqlSetOperators, union4, unionAll3, intersect3, intersectAll2, except3, exceptAll2;
var init_select4 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/select.js"() {
    "use strict";
    init_entity();
    init_table4();
    init_query_builder();
    init_query_promise();
    init_selection_proxy();
    init_sql();
    init_subquery();
    init_table();
    init_utils2();
    init_view_common();
    init_utils8();
    init_view_base3();
    _a325 = entityKind;
    MySqlSelectBuilder = class {
      constructor(config) {
        __publicField(this, "fields");
        __publicField(this, "session");
        __publicField(this, "dialect");
        __publicField(this, "withList", []);
        __publicField(this, "distinct");
        this.fields = config.fields;
        this.session = config.session;
        this.dialect = config.dialect;
        if (config.withList) {
          this.withList = config.withList;
        }
        this.distinct = config.distinct;
      }
      from(source, onIndex) {
        const isPartialSelect = !!this.fields;
        let fields;
        if (this.fields) {
          fields = this.fields;
        } else if (is(source, Subquery)) {
          fields = Object.fromEntries(
            Object.keys(source._.selectedFields).map((key) => [key, source[key]])
          );
        } else if (is(source, MySqlViewBase)) {
          fields = source[ViewBaseConfig].selectedFields;
        } else if (is(source, SQL)) {
          fields = {};
        } else {
          fields = getTableColumns(source);
        }
        let useIndex = [];
        let forceIndex = [];
        let ignoreIndex = [];
        if (is(source, MySqlTable) && onIndex && typeof onIndex !== "string") {
          if (onIndex.useIndex) {
            useIndex = convertIndexToString(toArray(onIndex.useIndex));
          }
          if (onIndex.forceIndex) {
            forceIndex = convertIndexToString(toArray(onIndex.forceIndex));
          }
          if (onIndex.ignoreIndex) {
            ignoreIndex = convertIndexToString(toArray(onIndex.ignoreIndex));
          }
        }
        return new MySqlSelectBase(
          {
            table: source,
            fields,
            isPartialSelect,
            session: this.session,
            dialect: this.dialect,
            withList: this.withList,
            distinct: this.distinct,
            useIndex,
            forceIndex,
            ignoreIndex
          }
        );
      }
    };
    __publicField(MySqlSelectBuilder, _a325, "MySqlSelectBuilder");
    MySqlSelectQueryBuilderBase = class extends (_b241 = TypedQueryBuilder, _a326 = entityKind, _b241) {
      constructor({ table: table6, fields, isPartialSelect, session, dialect: dialect6, withList, distinct, useIndex, forceIndex, ignoreIndex }) {
        super();
        __publicField(this, "_");
        __publicField(this, "config");
        __publicField(this, "joinsNotNullableMap");
        __publicField(this, "tableName");
        __publicField(this, "isPartialSelect");
        /** @internal */
        __publicField(this, "session");
        __publicField(this, "dialect");
        __publicField(this, "cacheConfig");
        __publicField(this, "usedTables", /* @__PURE__ */ new Set());
        /**
         * Executes a `left join` operation by adding another table to the current query.
         *
         * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         * @param onIndex index hint.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select()
         *   .from(users)
         *   .leftJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .leftJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId with use index hint
         * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .leftJoin(pets, eq(users.id, pets.ownerId), {
         *     useIndex: ['pets_owner_id_index']
         * })
         * ```
         */
        __publicField(this, "leftJoin", this.createJoin("left", false));
        /**
         * Executes a `left join lateral` operation by adding subquery to the current query.
         *
         * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
         *
         * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#left-join-lateral}
         *
         * @param table the subquery to join.
         * @param on the `on` clause.
         */
        __publicField(this, "leftJoinLateral", this.createJoin("left", true));
        /**
         * Executes a `right join` operation by adding another table to the current query.
         *
         * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         * @param onIndex index hint.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select()
         *   .from(users)
         *   .rightJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .rightJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId with use index hint
         * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .leftJoin(pets, eq(users.id, pets.ownerId), {
         *     useIndex: ['pets_owner_id_index']
         * })
         * ```
         */
        __publicField(this, "rightJoin", this.createJoin("right", false));
        /**
         * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
         *
         * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         * @param onIndex index hint.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
         *   .from(users)
         *   .innerJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .innerJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId with use index hint
         * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .leftJoin(pets, eq(users.id, pets.ownerId), {
         *     useIndex: ['pets_owner_id_index']
         * })
         * ```
         */
        __publicField(this, "innerJoin", this.createJoin("inner", false));
        /**
         * Executes an `inner join lateral` operation, creating a new table by combining rows from two queries that have matching values.
         *
         * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
         *
         * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join-lateral}
         *
         * @param table the subquery to join.
         * @param on the `on` clause.
         */
        __publicField(this, "innerJoinLateral", this.createJoin("inner", true));
        /**
         * Executes a `cross join` operation by combining rows from two tables into a new table.
         *
         * Calling this method retrieves all rows from both main and joined tables, merging all rows from each table.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
         *
         * @param table the table to join.
         * @param onIndex index hint.
         *
         * @example
         *
         * ```ts
         * // Select all users, each user with every pet
         * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
         *   .from(users)
         *   .crossJoin(pets)
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .crossJoin(pets)
         *
         * // Select userId and petId with use index hint
         * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .crossJoin(pets, {
         *     useIndex: ['pets_owner_id_index']
         * })
         * ```
         */
        __publicField(this, "crossJoin", this.createJoin("cross", false));
        /**
         * Executes a `cross join lateral` operation by combining rows from two queries into a new table.
         *
         * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
         *
         * Calling this method retrieves all rows from both main and joined queries, merging all rows from each query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join-lateral}
         *
         * @param table the query to join.
         */
        __publicField(this, "crossJoinLateral", this.createJoin("cross", true));
        /**
         * Adds `union` set operator to the query.
         *
         * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
         *
         * @example
         *
         * ```ts
         * // Select all unique names from customers and users tables
         * await db.select({ name: users.name })
         *   .from(users)
         *   .union(
         *     db.select({ name: customers.name }).from(customers)
         *   );
         * // or
         * import { union } from 'drizzle-orm/mysql-core'
         *
         * await union(
         *   db.select({ name: users.name }).from(users),
         *   db.select({ name: customers.name }).from(customers)
         * );
         * ```
         */
        __publicField(this, "union", this.createSetOperator("union", false));
        /**
         * Adds `union all` set operator to the query.
         *
         * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
         *
         * @example
         *
         * ```ts
         * // Select all transaction ids from both online and in-store sales
         * await db.select({ transaction: onlineSales.transactionId })
         *   .from(onlineSales)
         *   .unionAll(
         *     db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
         *   );
         * // or
         * import { unionAll } from 'drizzle-orm/mysql-core'
         *
         * await unionAll(
         *   db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
         *   db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
         * );
         * ```
         */
        __publicField(this, "unionAll", this.createSetOperator("union", true));
        /**
         * Adds `intersect` set operator to the query.
         *
         * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
         *
         * @example
         *
         * ```ts
         * // Select course names that are offered in both departments A and B
         * await db.select({ courseName: depA.courseName })
         *   .from(depA)
         *   .intersect(
         *     db.select({ courseName: depB.courseName }).from(depB)
         *   );
         * // or
         * import { intersect } from 'drizzle-orm/mysql-core'
         *
         * await intersect(
         *   db.select({ courseName: depA.courseName }).from(depA),
         *   db.select({ courseName: depB.courseName }).from(depB)
         * );
         * ```
         */
        __publicField(this, "intersect", this.createSetOperator("intersect", false));
        /**
         * Adds `intersect all` set operator to the query.
         *
         * Calling this method will retain only the rows that are present in both result sets including all duplicates.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}
         *
         * @example
         *
         * ```ts
         * // Select all products and quantities that are ordered by both regular and VIP customers
         * await db.select({
         *   productId: regularCustomerOrders.productId,
         *   quantityOrdered: regularCustomerOrders.quantityOrdered
         * })
         * .from(regularCustomerOrders)
         * .intersectAll(
         *   db.select({
         *     productId: vipCustomerOrders.productId,
         *     quantityOrdered: vipCustomerOrders.quantityOrdered
         *   })
         *   .from(vipCustomerOrders)
         * );
         * // or
         * import { intersectAll } from 'drizzle-orm/mysql-core'
         *
         * await intersectAll(
         *   db.select({
         *     productId: regularCustomerOrders.productId,
         *     quantityOrdered: regularCustomerOrders.quantityOrdered
         *   })
         *   .from(regularCustomerOrders),
         *   db.select({
         *     productId: vipCustomerOrders.productId,
         *     quantityOrdered: vipCustomerOrders.quantityOrdered
         *   })
         *   .from(vipCustomerOrders)
         * );
         * ```
         */
        __publicField(this, "intersectAll", this.createSetOperator("intersect", true));
        /**
         * Adds `except` set operator to the query.
         *
         * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
         *
         * @example
         *
         * ```ts
         * // Select all courses offered in department A but not in department B
         * await db.select({ courseName: depA.courseName })
         *   .from(depA)
         *   .except(
         *     db.select({ courseName: depB.courseName }).from(depB)
         *   );
         * // or
         * import { except } from 'drizzle-orm/mysql-core'
         *
         * await except(
         *   db.select({ courseName: depA.courseName }).from(depA),
         *   db.select({ courseName: depB.courseName }).from(depB)
         * );
         * ```
         */
        __publicField(this, "except", this.createSetOperator("except", false));
        /**
         * Adds `except all` set operator to the query.
         *
         * Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}
         *
         * @example
         *
         * ```ts
         * // Select all products that are ordered by regular customers but not by VIP customers
         * await db.select({
         *   productId: regularCustomerOrders.productId,
         *   quantityOrdered: regularCustomerOrders.quantityOrdered,
         * })
         * .from(regularCustomerOrders)
         * .exceptAll(
         *   db.select({
         *     productId: vipCustomerOrders.productId,
         *     quantityOrdered: vipCustomerOrders.quantityOrdered,
         *   })
         *   .from(vipCustomerOrders)
         * );
         * // or
         * import { exceptAll } from 'drizzle-orm/mysql-core'
         *
         * await exceptAll(
         *   db.select({
         *     productId: regularCustomerOrders.productId,
         *     quantityOrdered: regularCustomerOrders.quantityOrdered
         *   })
         *   .from(regularCustomerOrders),
         *   db.select({
         *     productId: vipCustomerOrders.productId,
         *     quantityOrdered: vipCustomerOrders.quantityOrdered
         *   })
         *   .from(vipCustomerOrders)
         * );
         * ```
         */
        __publicField(this, "exceptAll", this.createSetOperator("except", true));
        this.config = {
          withList,
          table: table6,
          fields: { ...fields },
          distinct,
          setOperators: [],
          useIndex,
          forceIndex,
          ignoreIndex
        };
        this.isPartialSelect = isPartialSelect;
        this.session = session;
        this.dialect = dialect6;
        this._ = {
          selectedFields: fields,
          config: this.config
        };
        this.tableName = getTableLikeName(table6);
        this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
        for (const item of extractUsedTable3(table6)) this.usedTables.add(item);
      }
      /** @internal */
      getUsedTables() {
        return [...this.usedTables];
      }
      createJoin(joinType, lateral) {
        return (table6, a, b) => {
          const isCrossJoin = joinType === "cross";
          let on = isCrossJoin ? void 0 : a;
          const onIndex = isCrossJoin ? a : b;
          const baseTableName = this.tableName;
          const tableName = getTableLikeName(table6);
          for (const item of extractUsedTable3(table6)) this.usedTables.add(item);
          if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
            throw new Error(`Alias "${tableName}" is already used in this query`);
          }
          if (!this.isPartialSelect) {
            if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
              this.config.fields = {
                [baseTableName]: this.config.fields
              };
            }
            if (typeof tableName === "string" && !is(table6, SQL)) {
              const selection = is(table6, Subquery) ? table6._.selectedFields : is(table6, View3) ? table6[ViewBaseConfig].selectedFields : table6[Table2.Symbol.Columns];
              this.config.fields[tableName] = selection;
            }
          }
          if (typeof on === "function") {
            on = on(
              new Proxy(
                this.config.fields,
                new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
              )
            );
          }
          if (!this.config.joins) {
            this.config.joins = [];
          }
          let useIndex = [];
          let forceIndex = [];
          let ignoreIndex = [];
          if (is(table6, MySqlTable) && onIndex && typeof onIndex !== "string") {
            if (onIndex.useIndex) {
              useIndex = convertIndexToString(toArray(onIndex.useIndex));
            }
            if (onIndex.forceIndex) {
              forceIndex = convertIndexToString(toArray(onIndex.forceIndex));
            }
            if (onIndex.ignoreIndex) {
              ignoreIndex = convertIndexToString(toArray(onIndex.ignoreIndex));
            }
          }
          this.config.joins.push({ on, table: table6, joinType, alias: tableName, useIndex, forceIndex, ignoreIndex, lateral });
          if (typeof tableName === "string") {
            switch (joinType) {
              case "left": {
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
              case "right": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "cross":
              case "inner": {
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
            }
          }
          return this;
        };
      }
      createSetOperator(type, isAll) {
        return (rightSelection) => {
          const rightSelect = typeof rightSelection === "function" ? rightSelection(getMySqlSetOperators()) : rightSelection;
          if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {
            throw new Error(
              "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
            );
          }
          this.config.setOperators.push({ type, isAll, rightSelect });
          return this;
        };
      }
      /** @internal */
      addSetOperators(setOperators) {
        this.config.setOperators.push(...setOperators);
        return this;
      }
      /**
       * Adds a `where` clause to the query.
       *
       * Calling this method will select only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#filtering}
       *
       * @param where the `where` clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be selected.
       *
       * ```ts
       * // Select all cars with green color
       * await db.select().from(cars).where(eq(cars.color, 'green'));
       * // or
       * await db.select().from(cars).where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Select all BMW cars with a green color
       * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Select all cars with the green or blue color
       * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        if (typeof where === "function") {
          where = where(
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
            )
          );
        }
        this.config.where = where;
        return this;
      }
      /**
       * Adds a `having` clause to the query.
       *
       * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
       *
       * @param having the `having` clause.
       *
       * @example
       *
       * ```ts
       * // Select all brands with more than one car
       * await db.select({
       * 	brand: cars.brand,
       * 	count: sql<number>`cast(count(${cars.id}) as int)`,
       * })
       *   .from(cars)
       *   .groupBy(cars.brand)
       *   .having(({ count }) => gt(count, 1));
       * ```
       */
      having(having) {
        if (typeof having === "function") {
          having = having(
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
            )
          );
        }
        this.config.having = having;
        return this;
      }
      groupBy(...columns) {
        if (typeof columns[0] === "function") {
          const groupBy = columns[0](
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
        } else {
          this.config.groupBy = columns;
        }
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          if (this.config.setOperators.length > 0) {
            this.config.setOperators.at(-1).orderBy = orderByArray;
          } else {
            this.config.orderBy = orderByArray;
          }
        } else {
          const orderByArray = columns;
          if (this.config.setOperators.length > 0) {
            this.config.setOperators.at(-1).orderBy = orderByArray;
          } else {
            this.config.orderBy = orderByArray;
          }
        }
        return this;
      }
      /**
       * Adds a `limit` clause to the query.
       *
       * Calling this method will set the maximum number of rows that will be returned by this query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
       *
       * @param limit the `limit` clause.
       *
       * @example
       *
       * ```ts
       * // Get the first 10 people from this query.
       * await db.select().from(people).limit(10);
       * ```
       */
      limit(limit) {
        if (this.config.setOperators.length > 0) {
          this.config.setOperators.at(-1).limit = limit;
        } else {
          this.config.limit = limit;
        }
        return this;
      }
      /**
       * Adds an `offset` clause to the query.
       *
       * Calling this method will skip a number of rows when returning results from this query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
       *
       * @param offset the `offset` clause.
       *
       * @example
       *
       * ```ts
       * // Get the 10th-20th people from this query.
       * await db.select().from(people).offset(10).limit(10);
       * ```
       */
      offset(offset) {
        if (this.config.setOperators.length > 0) {
          this.config.setOperators.at(-1).offset = offset;
        } else {
          this.config.offset = offset;
        }
        return this;
      }
      /**
       * Adds a `for` clause to the query.
       *
       * Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried.
       *
       * See docs: {@link https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html}
       *
       * @param strength the lock strength.
       * @param config the lock configuration.
       */
      for(strength, config = {}) {
        this.config.lockingClause = { strength, config };
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildSelectQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      as(alias) {
        const usedTables = [];
        usedTables.push(...extractUsedTable3(this.config.table));
        if (this.config.joins) {
          for (const it of this.config.joins) usedTables.push(...extractUsedTable3(it.table));
        }
        return new Proxy(
          new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]),
          new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
        );
      }
      /** @internal */
      getSelectedFields() {
        return new Proxy(
          this.config.fields,
          new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
        );
      }
      $dynamic() {
        return this;
      }
      $withCache(config) {
        this.cacheConfig = config === void 0 ? { config: {}, enable: true, autoInvalidate: true } : config === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config };
        return this;
      }
    };
    __publicField(MySqlSelectQueryBuilderBase, _a326, "MySqlSelectQueryBuilder");
    MySqlSelectBase = class extends (_b242 = MySqlSelectQueryBuilderBase, _a327 = entityKind, _b242) {
      constructor() {
        super(...arguments);
        __publicField(this, "execute", (placeholderValues) => {
          return this.prepare().execute(placeholderValues);
        });
        __publicField(this, "createIterator", () => {
          const self2 = this;
          return async function* (placeholderValues) {
            yield* self2.prepare().iterator(placeholderValues);
          };
        });
        __publicField(this, "iterator", this.createIterator());
      }
      prepare() {
        if (!this.session) {
          throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
        }
        const fieldsList = orderSelectedFields(this.config.fields);
        const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), fieldsList, void 0, void 0, void 0, {
          type: "select",
          tables: [...this.usedTables]
        }, this.cacheConfig);
        query.joinsNotNullableMap = this.joinsNotNullableMap;
        return query;
      }
    };
    __publicField(MySqlSelectBase, _a327, "MySqlSelect");
    applyMixins(MySqlSelectBase, [QueryPromise]);
    getMySqlSetOperators = () => ({
      union: union4,
      unionAll: unionAll3,
      intersect: intersect3,
      intersectAll: intersectAll2,
      except: except3,
      exceptAll: exceptAll2
    });
    union4 = createSetOperator3("union", false);
    unionAll3 = createSetOperator3("union", true);
    intersect3 = createSetOperator3("intersect", false);
    intersectAll2 = createSetOperator3("intersect", true);
    except3 = createSetOperator3("except", false);
    exceptAll2 = createSetOperator3("except", true);
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/query-builder.js
var _a328, QueryBuilder3;
var init_query_builder4 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/query-builder.js"() {
    "use strict";
    init_entity();
    init_dialect3();
    init_selection_proxy();
    init_subquery();
    init_select4();
    _a328 = entityKind;
    QueryBuilder3 = class {
      constructor(dialect6) {
        __publicField(this, "dialect");
        __publicField(this, "dialectConfig");
        __publicField(this, "$with", (alias, selection) => {
          const queryBuilder = this;
          const as = (qb) => {
            if (typeof qb === "function") {
              qb = qb(queryBuilder);
            }
            return new Proxy(
              new WithSubquery(
                qb.getSQL(),
                selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
                alias,
                true
              ),
              new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
            );
          };
          return { as };
        });
        this.dialect = is(dialect6, MySqlDialect) ? dialect6 : void 0;
        this.dialectConfig = is(dialect6, MySqlDialect) ? void 0 : dialect6;
      }
      with(...queries) {
        const self2 = this;
        function select(fields) {
          return new MySqlSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self2.getDialect(),
            withList: queries
          });
        }
        function selectDistinct(fields) {
          return new MySqlSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self2.getDialect(),
            withList: queries,
            distinct: true
          });
        }
        return { select, selectDistinct };
      }
      select(fields) {
        return new MySqlSelectBuilder({ fields: fields ?? void 0, session: void 0, dialect: this.getDialect() });
      }
      selectDistinct(fields) {
        return new MySqlSelectBuilder({
          fields: fields ?? void 0,
          session: void 0,
          dialect: this.getDialect(),
          distinct: true
        });
      }
      // Lazy load dialect to avoid circular dependency
      getDialect() {
        if (!this.dialect) {
          this.dialect = new MySqlDialect(this.dialectConfig);
        }
        return this.dialect;
      }
    };
    __publicField(QueryBuilder3, _a328, "MySqlQueryBuilder");
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/insert.js
var _a329, MySqlInsertBuilder, _a330, _b243, MySqlInsertBase;
var init_insert3 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/insert.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_sql();
    init_table();
    init_utils2();
    init_utils8();
    init_query_builder4();
    _a329 = entityKind;
    MySqlInsertBuilder = class {
      constructor(table6, session, dialect6) {
        __publicField(this, "shouldIgnore", false);
        this.table = table6;
        this.session = session;
        this.dialect = dialect6;
      }
      ignore() {
        this.shouldIgnore = true;
        return this;
      }
      values(values) {
        values = Array.isArray(values) ? values : [values];
        if (values.length === 0) {
          throw new Error("values() must be called with at least one value");
        }
        const mappedValues = values.map((entry) => {
          const result = {};
          const cols = this.table[Table2.Symbol.Columns];
          for (const colKey of Object.keys(entry)) {
            const colValue = entry[colKey];
            result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
          }
          return result;
        });
        return new MySqlInsertBase(this.table, mappedValues, this.shouldIgnore, this.session, this.dialect);
      }
      select(selectQuery) {
        const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder3()) : selectQuery;
        if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) {
          throw new Error(
            "Insert select error: selected fields are not the same or are in a different order compared to the table definition"
          );
        }
        return new MySqlInsertBase(this.table, select, this.shouldIgnore, this.session, this.dialect, true);
      }
    };
    __publicField(MySqlInsertBuilder, _a329, "MySqlInsertBuilder");
    MySqlInsertBase = class extends (_b243 = QueryPromise, _a330 = entityKind, _b243) {
      constructor(table6, values, ignore, session, dialect6, select) {
        super();
        __publicField(this, "config");
        __publicField(this, "cacheConfig");
        __publicField(this, "execute", (placeholderValues) => {
          return this.prepare().execute(placeholderValues);
        });
        __publicField(this, "createIterator", () => {
          const self2 = this;
          return async function* (placeholderValues) {
            yield* self2.prepare().iterator(placeholderValues);
          };
        });
        __publicField(this, "iterator", this.createIterator());
        this.session = session;
        this.dialect = dialect6;
        this.config = { table: table6, values, select, ignore };
      }
      /**
       * Adds an `on duplicate key update` clause to the query.
       *
       * Calling this method will update the row if any unique index conflicts. MySQL will automatically determine the conflict target based on the primary key and unique indexes.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert#on-duplicate-key-update}
       *
       * @param config The `set` clause
       *
       * @example
       * ```ts
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW'})
       *   .onDuplicateKeyUpdate({ set: { brand: 'Porsche' }});
       * ```
       *
       * While MySQL does not directly support doing nothing on conflict, you can perform a no-op by setting any column's value to itself and achieve the same effect:
       *
       * ```ts
       * import { sql } from 'drizzle-orm';
       *
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onDuplicateKeyUpdate({ set: { id: sql`id` } });
       * ```
       */
      onDuplicateKeyUpdate(config) {
        const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
        this.config.onConflict = sql`update ${setSql}`;
        return this;
      }
      $returningId() {
        const returning = [];
        for (const [key, value] of Object.entries(this.config.table[Table2.Symbol.Columns])) {
          if (value.primary) {
            returning.push({ field: value, path: [key] });
          }
        }
        this.config.returning = returning;
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildInsertQuery(this.config).sql;
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      prepare() {
        const { sql: sql2, generatedIds } = this.dialect.buildInsertQuery(this.config);
        return this.session.prepareQuery(
          this.dialect.sqlToQuery(sql2),
          void 0,
          void 0,
          generatedIds,
          this.config.returning,
          {
            type: "insert",
            tables: extractUsedTable3(this.config.table)
          },
          this.cacheConfig
        );
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(MySqlInsertBase, _a330, "MySqlInsert");
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/select.types.js
var init_select_types3 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/select.types.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/update.js
var _a331, MySqlUpdateBuilder, _a332, _b244, MySqlUpdateBase;
var init_update3 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/update.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_selection_proxy();
    init_table();
    init_utils2();
    init_utils8();
    _a331 = entityKind;
    MySqlUpdateBuilder = class {
      constructor(table6, session, dialect6, withList) {
        this.table = table6;
        this.session = session;
        this.dialect = dialect6;
        this.withList = withList;
      }
      set(values) {
        return new MySqlUpdateBase(this.table, mapUpdateSet(this.table, values), this.session, this.dialect, this.withList);
      }
    };
    __publicField(MySqlUpdateBuilder, _a331, "MySqlUpdateBuilder");
    MySqlUpdateBase = class extends (_b244 = QueryPromise, _a332 = entityKind, _b244) {
      constructor(table6, set, session, dialect6, withList) {
        super();
        __publicField(this, "config");
        __publicField(this, "cacheConfig");
        __publicField(this, "execute", (placeholderValues) => {
          return this.prepare().execute(placeholderValues);
        });
        __publicField(this, "createIterator", () => {
          const self2 = this;
          return async function* (placeholderValues) {
            yield* self2.prepare().iterator(placeholderValues);
          };
        });
        __publicField(this, "iterator", this.createIterator());
        this.session = session;
        this.dialect = dialect6;
        this.config = { set, table: table6, withList };
      }
      /**
       * Adds a 'where' clause to the query.
       *
       * Calling this method will update only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/update}
       *
       * @param where the 'where' clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be updated.
       *
       * ```ts
       * // Update all cars with green color
       * db.update(cars).set({ color: 'red' })
       *   .where(eq(cars.color, 'green'));
       * // or
       * db.update(cars).set({ color: 'red' })
       *   .where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Update all BMW cars with a green color
       * db.update(cars).set({ color: 'red' })
       *   .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Update all cars with the green or blue color
       * db.update(cars).set({ color: 'red' })
       *   .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        this.config.where = where;
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.table[Table2.Symbol.Columns],
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          this.config.orderBy = orderByArray;
        } else {
          const orderByArray = columns;
          this.config.orderBy = orderByArray;
        }
        return this;
      }
      limit(limit) {
        this.config.limit = limit;
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildUpdateQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      prepare() {
        return this.session.prepareQuery(
          this.dialect.sqlToQuery(this.getSQL()),
          void 0,
          void 0,
          void 0,
          this.config.returning,
          {
            type: "insert",
            tables: extractUsedTable3(this.config.table)
          },
          this.cacheConfig
        );
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(MySqlUpdateBase, _a332, "MySqlUpdate");
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/index.js
var init_query_builders3 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/index.js"() {
    "use strict";
    init_delete3();
    init_insert3();
    init_query_builder4();
    init_select4();
    init_select_types3();
    init_update3();
  }
});

// ../drizzle-orm/dist/mysql-core/query-builders/query.js
var _a333, RelationalQueryBuilder3, _a334, _b245, MySqlRelationalQuery;
var init_query3 = __esm({
  "../drizzle-orm/dist/mysql-core/query-builders/query.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_relations();
    _a333 = entityKind;
    RelationalQueryBuilder3 = class {
      constructor(fullSchema, schema5, tableNamesMap, table6, tableConfig, dialect6, session, mode) {
        this.fullSchema = fullSchema;
        this.schema = schema5;
        this.tableNamesMap = tableNamesMap;
        this.table = table6;
        this.tableConfig = tableConfig;
        this.dialect = dialect6;
        this.session = session;
        this.mode = mode;
      }
      findMany(config) {
        return new MySqlRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config ? config : {},
          "many",
          this.mode
        );
      }
      findFirst(config) {
        return new MySqlRelationalQuery(
          this.fullSchema,
          this.schema,
          this.tableNamesMap,
          this.table,
          this.tableConfig,
          this.dialect,
          this.session,
          config ? { ...config, limit: 1 } : { limit: 1 },
          "first",
          this.mode
        );
      }
    };
    __publicField(RelationalQueryBuilder3, _a333, "MySqlRelationalQueryBuilder");
    MySqlRelationalQuery = class extends (_b245 = QueryPromise, _a334 = entityKind, _b245) {
      constructor(fullSchema, schema5, tableNamesMap, table6, tableConfig, dialect6, session, config, queryMode, mode) {
        super();
        this.fullSchema = fullSchema;
        this.schema = schema5;
        this.tableNamesMap = tableNamesMap;
        this.table = table6;
        this.tableConfig = tableConfig;
        this.dialect = dialect6;
        this.session = session;
        this.config = config;
        this.queryMode = queryMode;
        this.mode = mode;
      }
      prepare() {
        const { query, builtQuery } = this._toSQL();
        return this.session.prepareQuery(
          builtQuery,
          void 0,
          (rawRows) => {
            const rows = rawRows.map((row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection));
            if (this.queryMode === "first") {
              return rows[0];
            }
            return rows;
          }
        );
      }
      _getQuery() {
        const query = this.mode === "planetscale" ? this.dialect.buildRelationalQueryWithoutLateralSubqueries({
          fullSchema: this.fullSchema,
          schema: this.schema,
          tableNamesMap: this.tableNamesMap,
          table: this.table,
          tableConfig: this.tableConfig,
          queryConfig: this.config,
          tableAlias: this.tableConfig.tsName
        }) : this.dialect.buildRelationalQuery({
          fullSchema: this.fullSchema,
          schema: this.schema,
          tableNamesMap: this.tableNamesMap,
          table: this.table,
          tableConfig: this.tableConfig,
          queryConfig: this.config,
          tableAlias: this.tableConfig.tsName
        });
        return query;
      }
      _toSQL() {
        const query = this._getQuery();
        const builtQuery = this.dialect.sqlToQuery(query.sql);
        return { builtQuery, query };
      }
      /** @internal */
      getSQL() {
        return this._getQuery().sql;
      }
      toSQL() {
        return this._toSQL().builtQuery;
      }
      execute() {
        return this.prepare().execute();
      }
    };
    __publicField(MySqlRelationalQuery, _a334, "MySqlRelationalQuery");
  }
});

// ../drizzle-orm/dist/mysql-core/db.js
var _a335, MySqlDatabase;
var init_db3 = __esm({
  "../drizzle-orm/dist/mysql-core/db.js"() {
    "use strict";
    init_entity();
    init_selection_proxy();
    init_sql();
    init_subquery();
    init_count3();
    init_query_builders3();
    init_query3();
    _a335 = entityKind;
    MySqlDatabase = class {
      constructor(dialect6, session, schema5, mode) {
        __publicField(this, "query");
        /**
         * Creates a subquery that defines a temporary named result set as a CTE.
         *
         * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
         *
         * @param alias The alias for the subquery.
         *
         * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
         *
         * @example
         *
         * ```ts
         * // Create a subquery with alias 'sq' and use it in the select query
         * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
         *
         * const result = await db.with(sq).select().from(sq);
         * ```
         *
         * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
         *
         * ```ts
         * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
         * const sq = db.$with('sq').as(db.select({
         *   name: sql<string>`upper(${users.name})`.as('name'),
         * })
         * .from(users));
         *
         * const result = await db.with(sq).select({ name: sq.name }).from(sq);
         * ```
         */
        __publicField(this, "$with", (alias, selection) => {
          const self2 = this;
          const as = (qb) => {
            if (typeof qb === "function") {
              qb = qb(new QueryBuilder3(self2.dialect));
            }
            return new Proxy(
              new WithSubquery(
                qb.getSQL(),
                selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
                alias,
                true
              ),
              new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
            );
          };
          return { as };
        });
        __publicField(this, "$cache");
        this.dialect = dialect6;
        this.session = session;
        this.mode = mode;
        this._ = schema5 ? {
          schema: schema5.schema,
          fullSchema: schema5.fullSchema,
          tableNamesMap: schema5.tableNamesMap
        } : {
          schema: void 0,
          fullSchema: {},
          tableNamesMap: {}
        };
        this.query = {};
        if (this._.schema) {
          for (const [tableName, columns] of Object.entries(this._.schema)) {
            this.query[tableName] = new RelationalQueryBuilder3(
              schema5.fullSchema,
              this._.schema,
              this._.tableNamesMap,
              schema5.fullSchema[tableName],
              columns,
              dialect6,
              session,
              this.mode
            );
          }
        }
        this.$cache = { invalidate: async (_params) => {
        } };
      }
      $count(source, filters) {
        return new MySqlCountBuilder({ source, filters, session: this.session });
      }
      /**
       * Incorporates a previously defined CTE (using `$with`) into the main query.
       *
       * This method allows the main query to reference a temporary named result set.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
       *
       * @param queries The CTEs to incorporate into the main query.
       *
       * @example
       *
       * ```ts
       * // Define a subquery 'sq' as a CTE using $with
       * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
       *
       * // Incorporate the CTE 'sq' into the main query and select from it
       * const result = await db.with(sq).select().from(sq);
       * ```
       */
      with(...queries) {
        const self2 = this;
        function select(fields) {
          return new MySqlSelectBuilder({
            fields: fields ?? void 0,
            session: self2.session,
            dialect: self2.dialect,
            withList: queries
          });
        }
        function selectDistinct(fields) {
          return new MySqlSelectBuilder({
            fields: fields ?? void 0,
            session: self2.session,
            dialect: self2.dialect,
            withList: queries,
            distinct: true
          });
        }
        function update(table6) {
          return new MySqlUpdateBuilder(table6, self2.session, self2.dialect, queries);
        }
        function delete_(table6) {
          return new MySqlDeleteBase(table6, self2.session, self2.dialect, queries);
        }
        return { select, selectDistinct, update, delete: delete_ };
      }
      select(fields) {
        return new MySqlSelectBuilder({ fields: fields ?? void 0, session: this.session, dialect: this.dialect });
      }
      selectDistinct(fields) {
        return new MySqlSelectBuilder({
          fields: fields ?? void 0,
          session: this.session,
          dialect: this.dialect,
          distinct: true
        });
      }
      /**
       * Creates an update query.
       *
       * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
       *
       * Use `.set()` method to specify which values to update.
       *
       * See docs: {@link https://orm.drizzle.team/docs/update}
       *
       * @param table The table to update.
       *
       * @example
       *
       * ```ts
       * // Update all rows in the 'cars' table
       * await db.update(cars).set({ color: 'red' });
       *
       * // Update rows with filters and conditions
       * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
       * ```
       */
      update(table6) {
        return new MySqlUpdateBuilder(table6, this.session, this.dialect);
      }
      /**
       * Creates an insert query.
       *
       * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert}
       *
       * @param table The table to insert into.
       *
       * @example
       *
       * ```ts
       * // Insert one row
       * await db.insert(cars).values({ brand: 'BMW' });
       *
       * // Insert multiple rows
       * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
       * ```
       */
      insert(table6) {
        return new MySqlInsertBuilder(table6, this.session, this.dialect);
      }
      /**
       * Creates a delete query.
       *
       * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
       *
       * See docs: {@link https://orm.drizzle.team/docs/delete}
       *
       * @param table The table to delete from.
       *
       * @example
       *
       * ```ts
       * // Delete all rows in the 'cars' table
       * await db.delete(cars);
       *
       * // Delete rows with filters and conditions
       * await db.delete(cars).where(eq(cars.color, 'green'));
       * ```
       */
      delete(table6) {
        return new MySqlDeleteBase(table6, this.session, this.dialect);
      }
      execute(query) {
        return this.session.execute(typeof query === "string" ? sql.raw(query) : query.getSQL());
      }
      transaction(transaction, config) {
        return this.session.transaction(transaction, config);
      }
    };
    __publicField(MySqlDatabase, _a335, "MySqlDatabase");
  }
});

// ../drizzle-orm/dist/mysql-core/view.js
function mysqlViewWithSchema(name2, selection, schema5) {
  if (selection) {
    return new ManualViewBuilder3(name2, selection, schema5);
  }
  return new ViewBuilder3(name2, schema5);
}
var _a336, ViewBuilderCore2, _a337, _b246, ViewBuilder3, _a338, _b247, ManualViewBuilder3, _a339, _b248, _c11, MySqlView2;
var init_view3 = __esm({
  "../drizzle-orm/dist/mysql-core/view.js"() {
    "use strict";
    init_entity();
    init_selection_proxy();
    init_utils2();
    init_query_builder4();
    init_table4();
    init_view_base3();
    init_view_common3();
    _a336 = entityKind;
    ViewBuilderCore2 = class {
      constructor(name2, schema5) {
        __publicField(this, "config", {});
        this.name = name2;
        this.schema = schema5;
      }
      algorithm(algorithm) {
        this.config.algorithm = algorithm;
        return this;
      }
      sqlSecurity(sqlSecurity) {
        this.config.sqlSecurity = sqlSecurity;
        return this;
      }
      withCheckOption(withCheckOption) {
        this.config.withCheckOption = withCheckOption ?? "cascaded";
        return this;
      }
    };
    __publicField(ViewBuilderCore2, _a336, "MySqlViewBuilder");
    ViewBuilder3 = class extends (_b246 = ViewBuilderCore2, _a337 = entityKind, _b246) {
      as(qb) {
        if (typeof qb === "function") {
          qb = qb(new QueryBuilder3());
        }
        const selectionProxy = new SelectionProxyHandler({
          alias: this.name,
          sqlBehavior: "error",
          sqlAliasedBehavior: "alias",
          replaceOriginalName: true
        });
        const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);
        return new Proxy(
          new MySqlView2({
            mysqlConfig: this.config,
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: aliasedSelection,
              query: qb.getSQL().inlineParams()
            }
          }),
          selectionProxy
        );
      }
    };
    __publicField(ViewBuilder3, _a337, "MySqlViewBuilder");
    ManualViewBuilder3 = class extends (_b247 = ViewBuilderCore2, _a338 = entityKind, _b247) {
      constructor(name2, columns, schema5) {
        super(name2, schema5);
        __publicField(this, "columns");
        this.columns = getTableColumns(mysqlTable(name2, columns));
      }
      existing() {
        return new Proxy(
          new MySqlView2({
            mysqlConfig: void 0,
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: this.columns,
              query: void 0
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
      as(query) {
        return new Proxy(
          new MySqlView2({
            mysqlConfig: this.config,
            config: {
              name: this.name,
              schema: this.schema,
              selectedFields: this.columns,
              query: query.inlineParams()
            }
          }),
          new SelectionProxyHandler({
            alias: this.name,
            sqlBehavior: "error",
            sqlAliasedBehavior: "alias",
            replaceOriginalName: true
          })
        );
      }
    };
    __publicField(ManualViewBuilder3, _a338, "MySqlManualViewBuilder");
    MySqlView2 = class extends (_c11 = MySqlViewBase, _b248 = entityKind, _a339 = MySqlViewConfig, _c11) {
      constructor({ mysqlConfig, config }) {
        super(config);
        __publicField(this, _a339);
        this[MySqlViewConfig] = mysqlConfig;
      }
    };
    __publicField(MySqlView2, _b248, "MySqlView");
  }
});

// ../drizzle-orm/dist/mysql-core/schema.js
var _a340, MySqlSchema5;
var init_schema2 = __esm({
  "../drizzle-orm/dist/mysql-core/schema.js"() {
    "use strict";
    init_entity();
    init_table4();
    init_view3();
    _a340 = entityKind;
    MySqlSchema5 = class {
      constructor(schemaName) {
        __publicField(this, "table", (name2, columns, extraConfig) => {
          return mysqlTableWithSchema(name2, columns, extraConfig, this.schemaName);
        });
        __publicField(this, "view", (name2, columns) => {
          return mysqlViewWithSchema(name2, columns, this.schemaName);
        });
        this.schemaName = schemaName;
      }
    };
    __publicField(MySqlSchema5, _a340, "MySqlSchema");
  }
});

// ../drizzle-orm/dist/mysql-core/session.js
var _a341, MySqlPreparedQuery, _a342, MySqlSession, _a343, _b249, MySqlTransaction;
var init_session3 = __esm({
  "../drizzle-orm/dist/mysql-core/session.js"() {
    "use strict";
    init_cache();
    init_entity();
    init_errors2();
    init_errors3();
    init_sql();
    init_db3();
    _a341 = entityKind;
    MySqlPreparedQuery = class {
      constructor(cache, queryMetadata, cacheConfig) {
        /** @internal */
        __publicField(this, "joinsNotNullableMap");
        this.cache = cache;
        this.queryMetadata = queryMetadata;
        this.cacheConfig = cacheConfig;
        if (cache && cache.strategy() === "all" && cacheConfig === void 0) {
          this.cacheConfig = { enable: true, autoInvalidate: true };
        }
        if (!this.cacheConfig?.enable) {
          this.cacheConfig = void 0;
        }
      }
      /** @internal */
      async queryWithCache(queryString, params, query) {
        if (this.cache === void 0 || is(this.cache, NoopCache) || this.queryMetadata === void 0) {
          try {
            return await query();
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if (this.cacheConfig && !this.cacheConfig.enable) {
          try {
            return await query();
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) {
          try {
            const [res] = await Promise.all([
              query(),
              this.cache.onMutate({ tables: this.queryMetadata.tables })
            ]);
            return res;
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if (!this.cacheConfig) {
          try {
            return await query();
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if (this.queryMetadata.type === "select") {
          const fromCache = await this.cache.get(
            this.cacheConfig.tag ?? await hashQuery(queryString, params),
            this.queryMetadata.tables,
            this.cacheConfig.tag !== void 0,
            this.cacheConfig.autoInvalidate
          );
          if (fromCache === void 0) {
            let result;
            try {
              result = await query();
            } catch (e) {
              throw new DrizzleQueryError(queryString, params, e);
            }
            await this.cache.put(
              this.cacheConfig.tag ?? await hashQuery(queryString, params),
              result,
              // make sure we send tables that were used in a query only if user wants to invalidate it on each write
              this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [],
              this.cacheConfig.tag !== void 0,
              this.cacheConfig.config
            );
            return result;
          }
          return fromCache;
        }
        try {
          return await query();
        } catch (e) {
          throw new DrizzleQueryError(queryString, params, e);
        }
      }
    };
    __publicField(MySqlPreparedQuery, _a341, "MySqlPreparedQuery");
    _a342 = entityKind;
    MySqlSession = class {
      constructor(dialect6) {
        this.dialect = dialect6;
      }
      execute(query) {
        return this.prepareQuery(
          this.dialect.sqlToQuery(query),
          void 0
        ).execute();
      }
      async count(sql2) {
        const res = await this.execute(sql2);
        return Number(
          res[0][0]["count"]
        );
      }
      getSetTransactionSQL(config) {
        const parts = [];
        if (config.isolationLevel) {
          parts.push(`isolation level ${config.isolationLevel}`);
        }
        return parts.length ? sql`set transaction ${sql.raw(parts.join(" "))}` : void 0;
      }
      getStartTransactionSQL(config) {
        const parts = [];
        if (config.withConsistentSnapshot) {
          parts.push("with consistent snapshot");
        }
        if (config.accessMode) {
          parts.push(config.accessMode);
        }
        return parts.length ? sql`start transaction ${sql.raw(parts.join(" "))}` : void 0;
      }
    };
    __publicField(MySqlSession, _a342, "MySqlSession");
    MySqlTransaction = class extends (_b249 = MySqlDatabase, _a343 = entityKind, _b249) {
      constructor(dialect6, session, schema5, nestedIndex, mode) {
        super(dialect6, session, schema5, mode);
        this.schema = schema5;
        this.nestedIndex = nestedIndex;
      }
      rollback() {
        throw new TransactionRollbackError();
      }
    };
    __publicField(MySqlTransaction, _a343, "MySqlTransaction");
  }
});

// ../drizzle-orm/dist/mysql-core/subquery.js
var init_subquery4 = __esm({
  "../drizzle-orm/dist/mysql-core/subquery.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/mysql-core/index.js
var init_mysql_core = __esm({
  "../drizzle-orm/dist/mysql-core/index.js"() {
    "use strict";
    init_alias4();
    init_checks3();
    init_columns3();
    init_db3();
    init_dialect3();
    init_foreign_keys3();
    init_indexes3();
    init_primary_keys3();
    init_query_builders3();
    init_schema2();
    init_session3();
    init_subquery4();
    init_table4();
    init_unique_constraint3();
    init_utils8();
    init_view_common3();
    init_view3();
  }
});

// src/serializer/mysqlSerializer.ts
function clearDefaults(defaultValue, collate) {
  if (typeof collate === "undefined" || collate === null) {
    collate = `utf8mb4`;
  }
  let resultDefault = defaultValue;
  collate = `_${collate}`;
  if (defaultValue.startsWith(collate)) {
    resultDefault = resultDefault.substring(collate.length, defaultValue.length).replace(/\\/g, "");
    if (resultDefault.startsWith("'") && resultDefault.endsWith("'")) {
      return `('${escapeSingleQuotes(resultDefault.substring(1, resultDefault.length - 1))}')`;
    } else {
      return `'${escapeSingleQuotes(resultDefault.substring(1, resultDefault.length - 1))}'`;
    }
  } else {
    return `(${resultDefault})`;
  }
}
var handleEnumType, generateMySqlSnapshot, fromDatabase3;
var init_mysqlSerializer = __esm({
  "src/serializer/mysqlSerializer.ts"() {
    "use strict";
    init_source();
    init_dist();
    init_mysql_core();
    init_outputs();
    init_utils();
    init_utils6();
    handleEnumType = (type) => {
      let str = type.split("(")[1];
      str = str.substring(0, str.length - 1);
      const values = str.split(",").map((v) => `'${escapeSingleQuotes(v.substring(1, v.length - 1))}'`);
      return `enum(${values.join(",")})`;
    };
    generateMySqlSnapshot = (tables, views, casing2) => {
      const dialect6 = new MySqlDialect({ casing: casing2 });
      const result = {};
      const resultViews = {};
      const internal = { tables: {}, indexes: {} };
      for (const table6 of tables) {
        const {
          name: tableName,
          columns,
          indexes,
          foreignKeys,
          schema: schema5,
          checks,
          primaryKeys,
          uniqueConstraints
        } = getTableConfig3(table6);
        const columnsObject = {};
        const indexesObject = {};
        const foreignKeysObject = {};
        const primaryKeysObject = {};
        const uniqueConstraintObject = {};
        const checkConstraintObject = {};
        let checksInTable = {};
        columns.forEach((column6) => {
          const name2 = getColumnCasing(column6, casing2);
          const notNull = column6.notNull;
          const sqlType = column6.getSQLType();
          const sqlTypeLowered = sqlType.toLowerCase();
          const autoIncrement = typeof column6.autoIncrement === "undefined" ? false : column6.autoIncrement;
          const generated = column6.generated;
          const columnToSet = {
            name: name2,
            type: sqlType.startsWith("enum") ? handleEnumType(sqlType) : sqlType,
            primaryKey: false,
            // If field is autoincrement it's notNull by default
            // notNull: autoIncrement ? true : notNull,
            notNull,
            autoincrement: autoIncrement,
            onUpdate: column6.hasOnUpdateNow,
            generated: generated ? {
              as: is(generated.as, SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
              type: generated.mode ?? "stored"
            } : void 0
          };
          if (column6.primary) {
            primaryKeysObject[`${tableName}_${name2}`] = {
              name: `${tableName}_${name2}`,
              columns: [name2]
            };
          }
          if (column6.isUnique) {
            const existingUnique = uniqueConstraintObject[column6.uniqueName];
            if (typeof existingUnique !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
          The unique constraint ${source_default.underline.blue(
                  column6.uniqueName
                )} on the ${source_default.underline.blue(
                  name2
                )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`)}`
              );
              process.exit(1);
            }
            uniqueConstraintObject[column6.uniqueName] = {
              name: column6.uniqueName,
              columns: [columnToSet.name]
            };
          }
          if (column6.default !== void 0) {
            if (is(column6.default, SQL)) {
              columnToSet.default = sqlToStr(column6.default, casing2);
            } else {
              if (typeof column6.default === "string") {
                columnToSet.default = `'${escapeSingleQuotes(column6.default)}'`;
              } else {
                if (sqlTypeLowered === "json") {
                  columnToSet.default = `'${JSON.stringify(column6.default)}'`;
                } else if (column6.default instanceof Date) {
                  if (sqlTypeLowered === "date") {
                    columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`;
                  } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
                    columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                  }
                } else {
                  columnToSet.default = column6.default;
                }
              }
              if (["blob", "text", "json"].includes(column6.getSQLType())) {
                columnToSet.default = `(${columnToSet.default})`;
              }
            }
          }
          columnsObject[name2] = columnToSet;
        });
        primaryKeys.map((pk) => {
          const originalColumnNames = pk.columns.map((c) => c.name);
          const columnNames = pk.columns.map((c) => getColumnCasing(c, casing2));
          let name2 = pk.getName();
          if (casing2 !== void 0) {
            for (let i = 0; i < originalColumnNames.length; i++) {
              name2 = name2.replace(originalColumnNames[i], columnNames[i]);
            }
          }
          primaryKeysObject[name2] = {
            name: name2,
            columns: columnNames
          };
          for (const column6 of pk.columns) {
            columnsObject[getColumnCasing(column6, casing2)].notNull = true;
          }
        });
        uniqueConstraints?.map((unq) => {
          const columnNames = unq.columns.map((c) => getColumnCasing(c, casing2));
          const name2 = unq.name ?? uniqueKeyName3(table6, columnNames);
          const existingUnique = uniqueConstraintObject[name2];
          if (typeof existingUnique !== "undefined") {
            console.log(
              `
${withStyle.errorWarning(
                `We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
The unique constraint ${source_default.underline.blue(
                  name2
                )} on the ${source_default.underline.blue(
                  columnNames.join(",")
                )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`
              )}`
            );
            process.exit(1);
          }
          uniqueConstraintObject[name2] = {
            name: unq.name,
            columns: columnNames
          };
        });
        const fks = foreignKeys.map((fk5) => {
          const tableFrom = tableName;
          const onDelete = fk5.onDelete ?? "no action";
          const onUpdate = fk5.onUpdate ?? "no action";
          const reference = fk5.reference();
          const referenceFT = reference.foreignTable;
          const tableTo = getTableName(referenceFT);
          const originalColumnsFrom = reference.columns.map((it) => it.name);
          const columnsFrom = reference.columns.map((it) => getColumnCasing(it, casing2));
          const originalColumnsTo = reference.foreignColumns.map((it) => it.name);
          const columnsTo = reference.foreignColumns.map((it) => getColumnCasing(it, casing2));
          let name2 = fk5.getName();
          if (casing2 !== void 0) {
            for (let i = 0; i < originalColumnsFrom.length; i++) {
              name2 = name2.replace(originalColumnsFrom[i], columnsFrom[i]);
            }
            for (let i = 0; i < originalColumnsTo.length; i++) {
              name2 = name2.replace(originalColumnsTo[i], columnsTo[i]);
            }
          }
          return {
            name: name2,
            tableFrom,
            tableTo,
            columnsFrom,
            columnsTo,
            onDelete,
            onUpdate
          };
        });
        fks.forEach((it) => {
          foreignKeysObject[it.name] = it;
        });
        indexes.forEach((value) => {
          const columns2 = value.config.columns;
          const name2 = value.config.name;
          let indexColumns = columns2.map((it) => {
            if (is(it, SQL)) {
              const sql2 = dialect6.sqlToQuery(it, "indexes").sql;
              if (typeof internal.indexes[name2] === "undefined") {
                internal.indexes[name2] = {
                  columns: {
                    [sql2]: {
                      isExpression: true
                    }
                  }
                };
              } else {
                if (typeof internal.indexes[name2]?.columns[sql2] === "undefined") {
                  internal.indexes[name2].columns[sql2] = {
                    isExpression: true
                  };
                } else {
                  internal.indexes[name2].columns[sql2].isExpression = true;
                }
              }
              return sql2;
            } else {
              return `${getColumnCasing(it, casing2)}`;
            }
          });
          if (value.config.unique) {
            if (typeof uniqueConstraintObject[name2] !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated unique constraint names in ${source_default.underline.blue(
                    tableName
                  )} table. 
The unique index ${source_default.underline.blue(
                    name2
                  )} on the ${source_default.underline.blue(
                    indexColumns.join(",")
                  )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                    uniqueConstraintObject[name2].columns.join(",")
                  )} columns
`
                )}`
              );
              process.exit(1);
            }
          } else {
            if (typeof foreignKeysObject[name2] !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(
                  `In MySQL, when creating a foreign key, an index is automatically generated with the same name as the foreign key constraint.

We have encountered a collision between the index name on columns ${source_default.underline.blue(
                    indexColumns.join(",")
                  )} and the foreign key on columns ${source_default.underline.blue(
                    foreignKeysObject[name2].columnsFrom.join(",")
                  )}. Please change either the index name or the foreign key name. For more information, please refer to https://dev.mysql.com/doc/refman/8.0/en/constraint-foreign-key.html

            `
                )}`
              );
              process.exit(1);
            }
          }
          indexesObject[name2] = {
            name: name2,
            columns: indexColumns,
            isUnique: value.config.unique ?? false,
            using: value.config.using,
            algorithm: value.config.algorythm,
            lock: value.config.lock
          };
        });
        checks.forEach((check) => {
          check;
          const checkName = check.name;
          if (typeof checksInTable[tableName] !== "undefined") {
            if (checksInTable[tableName].includes(check.name)) {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated check constraint name in ${source_default.underline.blue(
                    tableName
                  )}. Please rename your check constraint in the ${source_default.underline.blue(
                    tableName
                  )} table`
                )}`
              );
              process.exit(1);
            }
            checksInTable[tableName].push(checkName);
          } else {
            checksInTable[tableName] = [check.name];
          }
          checkConstraintObject[checkName] = {
            name: checkName,
            value: dialect6.sqlToQuery(check.value).sql
          };
        });
        if (!schema5) {
          result[tableName] = {
            name: tableName,
            columns: columnsObject,
            indexes: indexesObject,
            foreignKeys: foreignKeysObject,
            compositePrimaryKeys: primaryKeysObject,
            uniqueConstraints: uniqueConstraintObject,
            checkConstraint: checkConstraintObject
          };
        }
      }
      for (const view5 of views) {
        const {
          isExisting,
          name: name2,
          query,
          schema: schema5,
          selectedFields,
          algorithm,
          sqlSecurity,
          withCheckOption
        } = getViewConfig3(view5);
        const columnsObject = {};
        const existingView = resultViews[name2];
        if (typeof existingView !== "undefined") {
          console.log(
            `
${withStyle.errorWarning(
              `We've found duplicated view name across ${source_default.underline.blue(
                schema5 ?? "public"
              )} schema. Please rename your view`
            )}`
          );
          process.exit(1);
        }
        for (const key in selectedFields) {
          if (is(selectedFields[key], MySqlColumn)) {
            const column6 = selectedFields[key];
            const notNull = column6.notNull;
            const sqlTypeLowered = column6.getSQLType().toLowerCase();
            const autoIncrement = typeof column6.autoIncrement === "undefined" ? false : column6.autoIncrement;
            const generated = column6.generated;
            const columnToSet = {
              name: column6.name,
              type: column6.getSQLType(),
              primaryKey: false,
              // If field is autoincrement it's notNull by default
              // notNull: autoIncrement ? true : notNull,
              notNull,
              autoincrement: autoIncrement,
              onUpdate: column6.hasOnUpdateNow,
              generated: generated ? {
                as: is(generated.as, SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
                type: generated.mode ?? "stored"
              } : void 0
            };
            if (column6.default !== void 0) {
              if (is(column6.default, SQL)) {
                columnToSet.default = sqlToStr(column6.default, casing2);
              } else {
                if (typeof column6.default === "string") {
                  columnToSet.default = `'${column6.default}'`;
                } else {
                  if (sqlTypeLowered === "json") {
                    columnToSet.default = `'${JSON.stringify(column6.default)}'`;
                  } else if (column6.default instanceof Date) {
                    if (sqlTypeLowered === "date") {
                      columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`;
                    } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
                      columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                    }
                  } else {
                    columnToSet.default = column6.default;
                  }
                }
                if (["blob", "text", "json"].includes(column6.getSQLType())) {
                  columnToSet.default = `(${columnToSet.default})`;
                }
              }
            }
            columnsObject[column6.name] = columnToSet;
          }
        }
        resultViews[name2] = {
          columns: columnsObject,
          name: name2,
          isExisting,
          definition: isExisting ? void 0 : dialect6.sqlToQuery(query).sql,
          withCheckOption,
          algorithm: algorithm ?? "undefined",
          // set default values
          sqlSecurity: sqlSecurity ?? "definer"
          // set default values
        };
      }
      return {
        version: "5",
        dialect: "mysql",
        tables: result,
        views: resultViews,
        _meta: {
          tables: {},
          columns: {}
        },
        internal
      };
    };
    fromDatabase3 = async (db, inputSchema, tablesFilter = (table6) => true, progressCallback) => {
      const result = {};
      const internals = { tables: {}, indexes: {} };
      const columns = await db.query(`select * from information_schema.columns
	where table_schema = '${inputSchema}' and table_name != '__drizzle_migrations'
	order by table_name, ordinal_position;`);
      const response = columns;
      const schemas = [];
      let columnsCount = 0;
      let tablesCount = /* @__PURE__ */ new Set();
      let indexesCount = 0;
      let foreignKeysCount = 0;
      let checksCount = 0;
      let viewsCount = 0;
      const idxs = await db.query(
        `select * from INFORMATION_SCHEMA.STATISTICS
	WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';`
      );
      const idxRows = idxs;
      for (const column6 of response) {
        if (!tablesFilter(column6["TABLE_NAME"])) continue;
        columnsCount += 1;
        if (progressCallback) {
          progressCallback("columns", columnsCount, "fetching");
        }
        const schema5 = column6["TABLE_SCHEMA"];
        const tableName = column6["TABLE_NAME"];
        tablesCount.add(`${schema5}.${tableName}`);
        if (progressCallback) {
          progressCallback("columns", tablesCount.size, "fetching");
        }
        const columnName = column6["COLUMN_NAME"];
        const isNullable = column6["IS_NULLABLE"] === "YES";
        const dataType = column6["DATA_TYPE"];
        const columnType = column6["COLUMN_TYPE"];
        const isPrimary = column6["COLUMN_KEY"] === "PRI";
        const columnDefault = column6["COLUMN_DEFAULT"];
        const collation = column6["CHARACTER_SET_NAME"];
        const geenratedExpression = column6["GENERATION_EXPRESSION"];
        let columnExtra = column6["EXTRA"];
        let isAutoincrement = false;
        let isDefaultAnExpression = false;
        if (typeof column6["EXTRA"] !== "undefined") {
          columnExtra = column6["EXTRA"];
          isAutoincrement = column6["EXTRA"] === "auto_increment";
          isDefaultAnExpression = column6["EXTRA"].includes("DEFAULT_GENERATED");
        }
        if (schema5 !== inputSchema) {
          schemas.push(schema5);
        }
        const table6 = result[tableName];
        let changedType = columnType;
        if (columnType === "bigint unsigned" && !isNullable && isAutoincrement) {
          const uniqueIdx = idxRows.filter(
            (it) => it["COLUMN_NAME"] === columnName && it["TABLE_NAME"] === tableName && it["NON_UNIQUE"] === 0
          );
          if (uniqueIdx && uniqueIdx.length === 1) {
            changedType = columnType.replace("bigint unsigned", "serial");
          }
        }
        if (columnType.includes("decimal(10,0)")) {
          changedType = columnType.replace("decimal(10,0)", "decimal");
        }
        let onUpdate = void 0;
        if (columnType.startsWith("timestamp") && typeof columnExtra !== "undefined" && columnExtra.includes("on update CURRENT_TIMESTAMP")) {
          onUpdate = true;
        }
        const newColumn = {
          default: columnDefault === null || columnDefault === void 0 ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) && !["decimal", "char", "varchar"].some((type) => columnType.startsWith(type)) ? Number(columnDefault) : isDefaultAnExpression ? clearDefaults(columnDefault, collation) : `'${escapeSingleQuotes(columnDefault)}'`,
          autoincrement: isAutoincrement,
          name: columnName,
          type: changedType,
          primaryKey: false,
          notNull: !isNullable,
          onUpdate,
          generated: geenratedExpression ? {
            as: geenratedExpression,
            type: columnExtra === "VIRTUAL GENERATED" ? "virtual" : "stored"
          } : void 0
        };
        if (isDefaultAnExpression) {
          if (typeof internals.tables[tableName] === "undefined") {
            internals.tables[tableName] = {
              columns: {
                [columnName]: {
                  isDefaultAnExpression: true
                }
              }
            };
          } else {
            if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
              internals.tables[tableName].columns[columnName] = {
                isDefaultAnExpression: true
              };
            } else {
              internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
            }
          }
        }
        if (!table6) {
          result[tableName] = {
            name: tableName,
            columns: {
              [columnName]: newColumn
            },
            compositePrimaryKeys: {},
            indexes: {},
            foreignKeys: {},
            uniqueConstraints: {},
            checkConstraint: {}
          };
        } else {
          result[tableName].columns[columnName] = newColumn;
        }
      }
      const tablePks = await db.query(
        `SELECT table_name, column_name, ordinal_position
  FROM information_schema.table_constraints t
  LEFT JOIN information_schema.key_column_usage k
  USING(constraint_name,table_schema,table_name)
  WHERE t.constraint_type='PRIMARY KEY'
      and table_name != '__drizzle_migrations'
      AND t.table_schema = '${inputSchema}'
      ORDER BY ordinal_position`
      );
      const tableToPk = {};
      const tableToPkRows = tablePks;
      for (const tableToPkRow of tableToPkRows) {
        const tableName = tableToPkRow["TABLE_NAME"];
        const columnName = tableToPkRow["COLUMN_NAME"];
        const position = tableToPkRow["ordinal_position"];
        if (typeof result[tableName] === "undefined") {
          continue;
        }
        if (typeof tableToPk[tableName] === "undefined") {
          tableToPk[tableName] = [columnName];
        } else {
          tableToPk[tableName].push(columnName);
        }
      }
      for (const [key, value] of Object.entries(tableToPk)) {
        result[key].compositePrimaryKeys = {
          [`${key}_${value.join("_")}`]: {
            name: `${key}_${value.join("_")}`,
            columns: value
          }
        };
      }
      if (progressCallback) {
        progressCallback("columns", columnsCount, "done");
        progressCallback("tables", tablesCount.size, "done");
      }
      try {
        const fks = await db.query(
          `SELECT 
      kcu.TABLE_SCHEMA,
      kcu.TABLE_NAME,
      kcu.CONSTRAINT_NAME,
      kcu.COLUMN_NAME,
      kcu.REFERENCED_TABLE_SCHEMA,
      kcu.REFERENCED_TABLE_NAME,
      kcu.REFERENCED_COLUMN_NAME,
      rc.UPDATE_RULE,
      rc.DELETE_RULE
  FROM 
      INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
  LEFT JOIN 
      information_schema.referential_constraints rc 
      ON kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
  WHERE kcu.TABLE_SCHEMA = '${inputSchema}' AND kcu.CONSTRAINT_NAME != 'PRIMARY' 
      AND kcu.REFERENCED_TABLE_NAME IS NOT NULL;`
        );
        const fkRows = fks;
        for (const fkRow of fkRows) {
          foreignKeysCount += 1;
          if (progressCallback) {
            progressCallback("fks", foreignKeysCount, "fetching");
          }
          const tableSchema = fkRow["TABLE_SCHEMA"];
          const tableName = fkRow["TABLE_NAME"];
          const constraintName = fkRow["CONSTRAINT_NAME"];
          const columnName = fkRow["COLUMN_NAME"];
          const refTableSchema = fkRow["REFERENCED_TABLE_SCHEMA"];
          const refTableName = fkRow["REFERENCED_TABLE_NAME"];
          const refColumnName = fkRow["REFERENCED_COLUMN_NAME"];
          const updateRule = fkRow["UPDATE_RULE"];
          const deleteRule = fkRow["DELETE_RULE"];
          const tableInResult = result[tableName];
          if (typeof tableInResult === "undefined") continue;
          if (typeof tableInResult.foreignKeys[constraintName] !== "undefined") {
            tableInResult.foreignKeys[constraintName].columnsFrom.push(columnName);
            tableInResult.foreignKeys[constraintName].columnsTo.push(
              refColumnName
            );
          } else {
            tableInResult.foreignKeys[constraintName] = {
              name: constraintName,
              tableFrom: tableName,
              tableTo: refTableName,
              columnsFrom: [columnName],
              columnsTo: [refColumnName],
              onDelete: deleteRule?.toLowerCase(),
              onUpdate: updateRule?.toLowerCase()
            };
          }
          tableInResult.foreignKeys[constraintName].columnsFrom = [
            ...new Set(tableInResult.foreignKeys[constraintName].columnsFrom)
          ];
          tableInResult.foreignKeys[constraintName].columnsTo = [
            ...new Set(tableInResult.foreignKeys[constraintName].columnsTo)
          ];
        }
      } catch (e) {
      }
      if (progressCallback) {
        progressCallback("fks", foreignKeysCount, "done");
      }
      for (const idxRow of idxRows) {
        const tableSchema = idxRow["TABLE_SCHEMA"];
        const tableName = idxRow["TABLE_NAME"];
        const constraintName = idxRow["INDEX_NAME"];
        const columnName = idxRow["COLUMN_NAME"];
        const isUnique = idxRow["NON_UNIQUE"] === 0;
        const tableInResult = result[tableName];
        if (typeof tableInResult === "undefined") continue;
        indexesCount += 1;
        if (progressCallback) {
          progressCallback("indexes", indexesCount, "fetching");
        }
        if (isUnique) {
          if (typeof tableInResult.uniqueConstraints[constraintName] !== "undefined") {
            tableInResult.uniqueConstraints[constraintName].columns.push(
              columnName
            );
          } else {
            tableInResult.uniqueConstraints[constraintName] = {
              name: constraintName,
              columns: [columnName]
            };
          }
        } else {
          if (typeof tableInResult.foreignKeys[constraintName] === "undefined") {
            if (typeof tableInResult.indexes[constraintName] !== "undefined") {
              tableInResult.indexes[constraintName].columns.push(columnName);
            } else {
              tableInResult.indexes[constraintName] = {
                name: constraintName,
                columns: [columnName],
                isUnique
              };
            }
          }
        }
      }
      const views = await db.query(
        `select * from INFORMATION_SCHEMA.VIEWS WHERE table_schema = '${inputSchema}';`
      );
      const resultViews = {};
      viewsCount = views.length;
      if (progressCallback) {
        progressCallback("views", viewsCount, "fetching");
      }
      for await (const view5 of views) {
        const viewName = view5["TABLE_NAME"];
        const definition = view5["VIEW_DEFINITION"];
        const withCheckOption = view5["CHECK_OPTION"] === "NONE" ? void 0 : view5["CHECK_OPTION"].toLowerCase();
        const sqlSecurity = view5["SECURITY_TYPE"].toLowerCase();
        const [createSqlStatement] = await db.query(`SHOW CREATE VIEW \`${viewName}\`;`);
        const algorithmMatch = createSqlStatement["Create View"].match(/ALGORITHM=([^ ]+)/);
        const algorithm = algorithmMatch ? algorithmMatch[1].toLowerCase() : void 0;
        const columns2 = result[viewName].columns;
        delete result[viewName];
        resultViews[viewName] = {
          columns: columns2,
          isExisting: false,
          name: viewName,
          algorithm,
          definition,
          sqlSecurity,
          withCheckOption
        };
      }
      if (progressCallback) {
        progressCallback("indexes", indexesCount, "done");
        progressCallback("enums", 0, "done");
        progressCallback("views", viewsCount, "done");
      }
      const checkConstraints = await db.query(
        `SELECT 
    tc.table_name, 
    tc.constraint_name, 
    cc.check_clause
FROM 
    information_schema.table_constraints tc
JOIN 
    information_schema.check_constraints cc 
    ON tc.constraint_name = cc.constraint_name
WHERE 
    tc.constraint_schema = '${inputSchema}'
AND 
    tc.constraint_type = 'CHECK';`
      );
      checksCount += checkConstraints.length;
      if (progressCallback) {
        progressCallback("checks", checksCount, "fetching");
      }
      for (const checkConstraintRow of checkConstraints) {
        const constraintName = checkConstraintRow["CONSTRAINT_NAME"];
        const constraintValue = checkConstraintRow["CHECK_CLAUSE"];
        const tableName = checkConstraintRow["TABLE_NAME"];
        const tableInResult = result[tableName];
        tableInResult.checkConstraint[constraintName] = {
          name: constraintName,
          value: constraintValue
        };
      }
      if (progressCallback) {
        progressCallback("checks", checksCount, "done");
      }
      return {
        version: "5",
        dialect: "mysql",
        tables: result,
        views: resultViews,
        _meta: {
          tables: {},
          columns: {}
        },
        internal: internals
      };
    };
  }
});

// src/cli/validations/cli.ts
var cliConfigGenerate, pushParams, pullParams, configCheck, cliConfigCheck;
var init_cli = __esm({
  "src/cli/validations/cli.ts"() {
    "use strict";
    init_esm();
    init_schemaValidator();
    init_common();
    cliConfigGenerate = objectType({
      dialect: dialect4.optional(),
      schema: unionType([stringType(), stringType().array()]).optional(),
      out: stringType().optional().default("./drizzle"),
      config: stringType().optional(),
      name: stringType().optional(),
      prefix: prefix.optional(),
      breakpoints: booleanType().optional().default(true),
      custom: booleanType().optional().default(false)
    }).strict();
    pushParams = objectType({
      dialect: dialect4,
      casing: casingType.optional(),
      schema: unionType([stringType(), stringType().array()]),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]),
      extensionsFilters: literalType("postgis").array().optional(),
      verbose: booleanType().optional(),
      strict: booleanType().optional(),
      entities: objectType({
        roles: booleanType().or(objectType({
          provider: stringType().optional(),
          include: stringType().array().optional(),
          exclude: stringType().array().optional()
        })).optional().default(false)
      }).optional()
    }).passthrough();
    pullParams = objectType({
      config: stringType().optional(),
      dialect: dialect4,
      out: stringType().optional().default("drizzle"),
      tablesFilter: unionType([stringType(), stringType().array()]).optional(),
      schemaFilter: unionType([stringType(), stringType().array()]).optional().default(["public"]),
      extensionsFilters: literalType("postgis").array().optional(),
      casing,
      breakpoints: booleanType().optional().default(true),
      migrations: objectType({
        prefix: prefix.optional().default("index")
      }).optional(),
      entities: objectType({
        roles: booleanType().or(objectType({
          provider: stringType().optional(),
          include: stringType().array().optional(),
          exclude: stringType().array().optional()
        })).optional().default(false)
      }).optional()
    }).passthrough();
    configCheck = objectType({
      dialect: dialect4.optional(),
      out: stringType().optional()
    });
    cliConfigCheck = intersectionType(
      objectType({
        config: stringType().optional()
      }),
      configCheck
    );
  }
});

// src/cli/validations/gel.ts
var gelCredentials;
var init_gel = __esm({
  "src/cli/validations/gel.ts"() {
    "use strict";
    init_esm();
    init_views();
    init_common();
    gelCredentials = unionType([
      objectType({
        driver: undefinedType(),
        host: stringType().min(1),
        port: coerce.number().min(1).optional(),
        user: stringType().min(1).optional(),
        password: stringType().min(1).optional(),
        database: stringType().min(1),
        tlsSecurity: unionType([
          literalType("insecure"),
          literalType("no_host_verification"),
          literalType("strict"),
          literalType("default")
        ]).optional()
      }).transform((o) => {
        delete o.driver;
        return o;
      }),
      objectType({
        driver: undefinedType(),
        url: stringType().min(1),
        tlsSecurity: unionType([
          literalType("insecure"),
          literalType("no_host_verification"),
          literalType("strict"),
          literalType("default")
        ]).optional()
      }).transform((o) => {
        delete o.driver;
        return o;
      }),
      objectType({
        driver: undefinedType()
      }).transform((o) => {
        return void 0;
      })
    ]);
  }
});

// src/cli/validations/libsql.ts
var libSQLCredentials;
var init_libsql = __esm({
  "src/cli/validations/libsql.ts"() {
    "use strict";
    init_esm();
    init_views();
    init_common();
    libSQLCredentials = objectType({
      url: stringType().min(1),
      authToken: stringType().min(1).optional()
    });
  }
});

// src/cli/validations/mysql.ts
var mysqlCredentials;
var init_mysql = __esm({
  "src/cli/validations/mysql.ts"() {
    "use strict";
    init_esm();
    init_views();
    init_common();
    init_outputs();
    mysqlCredentials = unionType([
      objectType({
        host: stringType().min(1),
        port: coerce.number().min(1).optional(),
        user: stringType().min(1).optional(),
        password: stringType().min(1).optional(),
        database: stringType().min(1),
        ssl: unionType([
          stringType(),
          objectType({
            pfx: stringType().optional(),
            key: stringType().optional(),
            passphrase: stringType().optional(),
            cert: stringType().optional(),
            ca: unionType([stringType(), stringType().array()]).optional(),
            crl: unionType([stringType(), stringType().array()]).optional(),
            ciphers: stringType().optional(),
            rejectUnauthorized: booleanType().optional()
          })
        ]).optional()
      }),
      objectType({
        url: stringType().min(1)
      })
    ]);
  }
});

// src/cli/validations/postgres.ts
var postgresCredentials;
var init_postgres = __esm({
  "src/cli/validations/postgres.ts"() {
    "use strict";
    init_esm();
    init_views();
    init_common();
    postgresCredentials = unionType([
      objectType({
        driver: undefinedType(),
        host: stringType().min(1),
        port: coerce.number().min(1).optional(),
        user: stringType().min(1).optional(),
        password: stringType().min(1).optional(),
        database: stringType().min(1),
        ssl: unionType([
          literalType("require"),
          literalType("allow"),
          literalType("prefer"),
          literalType("verify-full"),
          booleanType(),
          objectType({}).passthrough()
        ]).optional()
      }).transform((o) => {
        delete o.driver;
        return o;
      }),
      objectType({
        driver: undefinedType(),
        url: stringType().min(1)
      }).transform((o) => {
        delete o.driver;
        return o;
      }),
      objectType({
        driver: literalType("aws-data-api"),
        database: stringType().min(1),
        secretArn: stringType().min(1),
        resourceArn: stringType().min(1)
      }),
      objectType({
        driver: literalType("pglite"),
        url: stringType().min(1)
      })
    ]);
  }
});

// src/cli/validations/singlestore.ts
var singlestoreCredentials;
var init_singlestore = __esm({
  "src/cli/validations/singlestore.ts"() {
    "use strict";
    init_esm();
    init_views();
    init_common();
    init_outputs();
    singlestoreCredentials = unionType([
      objectType({
        host: stringType().min(1),
        port: coerce.number().min(1).optional(),
        user: stringType().min(1).optional(),
        password: stringType().min(1).optional(),
        database: stringType().min(1),
        ssl: unionType([
          stringType(),
          objectType({
            pfx: stringType().optional(),
            key: stringType().optional(),
            passphrase: stringType().optional(),
            cert: stringType().optional(),
            ca: unionType([stringType(), stringType().array()]).optional(),
            crl: unionType([stringType(), stringType().array()]).optional(),
            ciphers: stringType().optional(),
            rejectUnauthorized: booleanType().optional()
          })
        ]).optional()
      }),
      objectType({
        url: stringType().min(1)
      })
    ]);
  }
});

// src/cli/validations/sqlite.ts
var sqliteCredentials;
var init_sqlite = __esm({
  "src/cli/validations/sqlite.ts"() {
    "use strict";
    init_global();
    init_esm();
    init_views();
    init_common();
    sqliteCredentials = unionType([
      objectType({
        driver: literalType("turso"),
        url: stringType().min(1),
        authToken: stringType().min(1).optional()
      }),
      objectType({
        driver: literalType("d1-http"),
        accountId: stringType().min(1),
        databaseId: stringType().min(1),
        token: stringType().min(1)
      }),
      objectType({
        driver: undefinedType(),
        url: stringType().min(1)
      }).transform((o) => {
        delete o.driver;
        return o;
      })
    ]);
  }
});

// src/cli/validations/studio.ts
var credentials, studioCliParams, studioConfig;
var init_studio = __esm({
  "src/cli/validations/studio.ts"() {
    "use strict";
    init_esm();
    init_schemaValidator();
    init_mysql();
    init_postgres();
    init_sqlite();
    credentials = intersectionType(
      postgresCredentials,
      mysqlCredentials,
      sqliteCredentials
    );
    studioCliParams = objectType({
      port: coerce.number().optional().default(4983),
      host: stringType().optional().default("127.0.0.1"),
      config: stringType().optional()
    });
    studioConfig = objectType({
      dialect: dialect4,
      schema: unionType([stringType(), stringType().array()]).optional()
    });
  }
});

// src/cli/commands/_es5.ts
var es5_exports = {};
__export(es5_exports, {
  default: () => es5_default
});
var _, es5_default;
var init_es5 = __esm({
  "src/cli/commands/_es5.ts"() {
    "use strict";
    _ = "";
    es5_default = _;
  }
});

// src/cli/commands/utils.ts
var import_hanji7, assertES5, safeRegister, migrateConfig;
var init_utils9 = __esm({
  "src/cli/commands/utils.ts"() {
    "use strict";
    import_hanji7 = __toESM(require_hanji());
    init_esm();
    init_getTablesFilterByExtensions();
    init_global();
    init_schemaValidator();
    init_serializer();
    init_cli();
    init_common();
    init_gel();
    init_gel();
    init_libsql();
    init_mysql();
    init_outputs();
    init_postgres();
    init_singlestore();
    init_sqlite();
    init_studio();
    init_views();
    assertES5 = async (unregister) => {
      try {
        init_es5();
      } catch (e) {
        if ("errors" in e && Array.isArray(e.errors) && e.errors.length > 0) {
          const es5Error = e.errors.filter((it) => it.text?.includes(`("es5") is not supported yet`)).length > 0;
          if (es5Error) {
            console.log(
              error(
                `Please change compilerOptions.target from 'es5' to 'es6' or above in your tsconfig.json`
              )
            );
            process.exit(1);
          }
        }
        console.error(e);
        process.exit(1);
      }
    };
    safeRegister = async () => {
      const { register } = await import("esbuild-register/dist/node");
      let res;
      try {
        res = register({
          format: "cjs",
          loader: "ts"
        });
      } catch {
        res = {
          unregister: () => {
          }
        };
      }
      await assertES5(res.unregister);
      return res;
    };
    migrateConfig = objectType({
      dialect: dialect4,
      out: stringType().optional().default("drizzle"),
      migrations: configMigrations
    });
  }
});

// src/serializer/pgImports.ts
var prepareFromExports;
var init_pgImports = __esm({
  "src/serializer/pgImports.ts"() {
    "use strict";
    init_dist();
    init_pg_core();
    init_utils9();
    prepareFromExports = (exports) => {
      const tables = [];
      const enums = [];
      const schemas = [];
      const sequences = [];
      const roles = [];
      const policies = [];
      const views = [];
      const matViews = [];
      const i0values = Object.values(exports);
      i0values.forEach((t) => {
        if (isPgEnum(t)) {
          enums.push(t);
          return;
        }
        if (is(t, PgTable)) {
          tables.push(t);
        }
        if (is(t, PgSchema5)) {
          schemas.push(t);
        }
        if (isPgView(t)) {
          views.push(t);
        }
        if (isPgMaterializedView(t)) {
          matViews.push(t);
        }
        if (isPgSequence(t)) {
          sequences.push(t);
        }
        if (is(t, PgRole)) {
          roles.push(t);
        }
        if (is(t, PgPolicy)) {
          policies.push(t);
        }
      });
      return { tables, enums, schemas, sequences, views, matViews, roles, policies };
    };
  }
});

// ../drizzle-orm/dist/singlestore-core/alias.js
var init_alias5 = __esm({
  "../drizzle-orm/dist/singlestore-core/alias.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/singlestore-core/unique-constraint.js
function uniqueKeyName4(table6, columns) {
  return `${table6[TableName]}_${columns.join("_")}_unique`;
}
var _a344, UniqueConstraintBuilder4, _a345, UniqueOnConstraintBuilder4, _a346, UniqueConstraint4;
var init_unique_constraint4 = __esm({
  "../drizzle-orm/dist/singlestore-core/unique-constraint.js"() {
    "use strict";
    init_entity();
    init_table_utils();
    _a344 = entityKind;
    UniqueConstraintBuilder4 = class {
      constructor(columns, name2) {
        /** @internal */
        __publicField(this, "columns");
        this.name = name2;
        this.columns = columns;
      }
      /** @internal */
      build(table6) {
        return new UniqueConstraint4(table6, this.columns, this.name);
      }
    };
    __publicField(UniqueConstraintBuilder4, _a344, "SingleStoreUniqueConstraintBuilder");
    _a345 = entityKind;
    UniqueOnConstraintBuilder4 = class {
      constructor(name2) {
        /** @internal */
        __publicField(this, "name");
        this.name = name2;
      }
      on(...columns) {
        return new UniqueConstraintBuilder4(columns, this.name);
      }
    };
    __publicField(UniqueOnConstraintBuilder4, _a345, "SingleStoreUniqueOnConstraintBuilder");
    _a346 = entityKind;
    UniqueConstraint4 = class {
      constructor(table6, columns, name2) {
        __publicField(this, "columns");
        __publicField(this, "name");
        __publicField(this, "nullsNotDistinct", false);
        this.table = table6;
        this.columns = columns;
        this.name = name2 ?? uniqueKeyName4(this.table, this.columns.map((column6) => column6.name));
      }
      getName() {
        return this.name;
      }
    };
    __publicField(UniqueConstraint4, _a346, "SingleStoreUniqueConstraint");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/common.js
var _a347, _b250, SingleStoreColumnBuilder, _a348, _b251, SingleStoreColumn, _a349, _b252, SingleStoreColumnBuilderWithAutoIncrement, _a350, _b253, SingleStoreColumnWithAutoIncrement;
var init_common5 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/common.js"() {
    "use strict";
    init_column_builder();
    init_column();
    init_entity();
    init_unique_constraint4();
    SingleStoreColumnBuilder = class extends (_b250 = ColumnBuilder, _a347 = entityKind, _b250) {
      unique(name2) {
        this.config.isUnique = true;
        this.config.uniqueName = name2;
        return this;
      }
      // TODO: Implement generated columns for SingleStore (https://docs.singlestore.com/cloud/create-a-database/using-persistent-computed-columns/)
      /** @internal */
      generatedAlwaysAs(as, config) {
        this.config.generated = {
          as,
          type: "always",
          mode: config?.mode ?? "virtual"
        };
        return this;
      }
    };
    __publicField(SingleStoreColumnBuilder, _a347, "SingleStoreColumnBuilder");
    SingleStoreColumn = class extends (_b251 = Column2, _a348 = entityKind, _b251) {
      constructor(table6, config) {
        if (!config.uniqueName) {
          config.uniqueName = uniqueKeyName4(table6, [config.name]);
        }
        super(table6, config);
        this.table = table6;
      }
    };
    __publicField(SingleStoreColumn, _a348, "SingleStoreColumn");
    SingleStoreColumnBuilderWithAutoIncrement = class extends (_b252 = SingleStoreColumnBuilder, _a349 = entityKind, _b252) {
      constructor(name2, dataType, columnType) {
        super(name2, dataType, columnType);
        this.config.autoIncrement = false;
      }
      autoincrement() {
        this.config.autoIncrement = true;
        this.config.hasDefault = true;
        return this;
      }
    };
    __publicField(SingleStoreColumnBuilderWithAutoIncrement, _a349, "SingleStoreColumnBuilderWithAutoIncrement");
    SingleStoreColumnWithAutoIncrement = class extends (_b253 = SingleStoreColumn, _a350 = entityKind, _b253) {
      constructor() {
        super(...arguments);
        __publicField(this, "autoIncrement", this.config.autoIncrement);
      }
    };
    __publicField(SingleStoreColumnWithAutoIncrement, _a350, "SingleStoreColumnWithAutoIncrement");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/bigint.js
function bigint3(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config.mode === "number") {
    return new SingleStoreBigInt53Builder(name2, config.unsigned);
  }
  return new SingleStoreBigInt64Builder(name2, config.unsigned);
}
var _a351, _b254, SingleStoreBigInt53Builder, _a352, _b255, SingleStoreBigInt53, _a353, _b256, SingleStoreBigInt64Builder, _a354, _b257, SingleStoreBigInt64;
var init_bigint3 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/bigint.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreBigInt53Builder = class extends (_b254 = SingleStoreColumnBuilderWithAutoIncrement, _a351 = entityKind, _b254) {
      constructor(name2, unsigned = false) {
        super(name2, "number", "SingleStoreBigInt53");
        this.config.unsigned = unsigned;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreBigInt53(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreBigInt53Builder, _a351, "SingleStoreBigInt53Builder");
    SingleStoreBigInt53 = class extends (_b255 = SingleStoreColumnWithAutoIncrement, _a352 = entityKind, _b255) {
      getSQLType() {
        return `bigint${this.config.unsigned ? " unsigned" : ""}`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "number") {
          return value;
        }
        return Number(value);
      }
    };
    __publicField(SingleStoreBigInt53, _a352, "SingleStoreBigInt53");
    SingleStoreBigInt64Builder = class extends (_b256 = SingleStoreColumnBuilderWithAutoIncrement, _a353 = entityKind, _b256) {
      constructor(name2, unsigned = false) {
        super(name2, "bigint", "SingleStoreBigInt64");
        this.config.unsigned = unsigned;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreBigInt64(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreBigInt64Builder, _a353, "SingleStoreBigInt64Builder");
    SingleStoreBigInt64 = class extends (_b257 = SingleStoreColumnWithAutoIncrement, _a354 = entityKind, _b257) {
      getSQLType() {
        return `bigint${this.config.unsigned ? " unsigned" : ""}`;
      }
      // eslint-disable-next-line unicorn/prefer-native-coercion-functions
      mapFromDriverValue(value) {
        return BigInt(value);
      }
    };
    __publicField(SingleStoreBigInt64, _a354, "SingleStoreBigInt64");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/binary.js
function binary2(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new SingleStoreBinaryBuilder(name2, config.length);
}
var _a355, _b258, SingleStoreBinaryBuilder, _a356, _b259, SingleStoreBinary;
var init_binary2 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/binary.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreBinaryBuilder = class extends (_b258 = SingleStoreColumnBuilder, _a355 = entityKind, _b258) {
      constructor(name2, length) {
        super(name2, "string", "SingleStoreBinary");
        this.config.length = length;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreBinary(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreBinaryBuilder, _a355, "SingleStoreBinaryBuilder");
    SingleStoreBinary = class extends (_b259 = SingleStoreColumn, _a356 = entityKind, _b259) {
      constructor() {
        super(...arguments);
        __publicField(this, "length", this.config.length);
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") return value;
        if (Buffer.isBuffer(value)) return value.toString();
        const str = [];
        for (const v of value) {
          str.push(v === 49 ? "1" : "0");
        }
        return str.join("");
      }
      getSQLType() {
        return this.length === void 0 ? `binary` : `binary(${this.length})`;
      }
    };
    __publicField(SingleStoreBinary, _a356, "SingleStoreBinary");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/boolean.js
function boolean3(name2) {
  return new SingleStoreBooleanBuilder(name2 ?? "");
}
var _a357, _b260, SingleStoreBooleanBuilder, _a358, _b261, SingleStoreBoolean;
var init_boolean3 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/boolean.js"() {
    "use strict";
    init_entity();
    init_common5();
    SingleStoreBooleanBuilder = class extends (_b260 = SingleStoreColumnBuilder, _a357 = entityKind, _b260) {
      constructor(name2) {
        super(name2, "boolean", "SingleStoreBoolean");
      }
      /** @internal */
      build(table6) {
        return new SingleStoreBoolean(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreBooleanBuilder, _a357, "SingleStoreBooleanBuilder");
    SingleStoreBoolean = class extends (_b261 = SingleStoreColumn, _a358 = entityKind, _b261) {
      getSQLType() {
        return "boolean";
      }
      mapFromDriverValue(value) {
        if (typeof value === "boolean") {
          return value;
        }
        return value === 1;
      }
    };
    __publicField(SingleStoreBoolean, _a358, "SingleStoreBoolean");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/char.js
function char3(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new SingleStoreCharBuilder(name2, config);
}
var _a359, _b262, SingleStoreCharBuilder, _a360, _b263, SingleStoreChar;
var init_char3 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/char.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreCharBuilder = class extends (_b262 = SingleStoreColumnBuilder, _a359 = entityKind, _b262) {
      constructor(name2, config) {
        super(name2, "string", "SingleStoreChar");
        this.config.length = config.length;
        this.config.enum = config.enum;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreChar(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreCharBuilder, _a359, "SingleStoreCharBuilder");
    SingleStoreChar = class extends (_b263 = SingleStoreColumn, _a360 = entityKind, _b263) {
      constructor() {
        super(...arguments);
        __publicField(this, "length", this.config.length);
        __publicField(this, "enumValues", this.config.enum);
      }
      getSQLType() {
        return this.length === void 0 ? `char` : `char(${this.length})`;
      }
    };
    __publicField(SingleStoreChar, _a360, "SingleStoreChar");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/custom.js
function customType4(customTypeParams) {
  return (a, b) => {
    const { name: name2, config } = getColumnNameAndConfig(a, b);
    return new SingleStoreCustomColumnBuilder(name2, config, customTypeParams);
  };
}
var _a361, _b264, SingleStoreCustomColumnBuilder, _a362, _b265, SingleStoreCustomColumn;
var init_custom4 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/custom.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreCustomColumnBuilder = class extends (_b264 = SingleStoreColumnBuilder, _a361 = entityKind, _b264) {
      constructor(name2, fieldConfig, customTypeParams) {
        super(name2, "custom", "SingleStoreCustomColumn");
        this.config.fieldConfig = fieldConfig;
        this.config.customTypeParams = customTypeParams;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreCustomColumn(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreCustomColumnBuilder, _a361, "SingleStoreCustomColumnBuilder");
    SingleStoreCustomColumn = class extends (_b265 = SingleStoreColumn, _a362 = entityKind, _b265) {
      constructor(table6, config) {
        super(table6, config);
        __publicField(this, "sqlName");
        __publicField(this, "mapTo");
        __publicField(this, "mapFrom");
        this.sqlName = config.customTypeParams.dataType(config.fieldConfig);
        this.mapTo = config.customTypeParams.toDriver;
        this.mapFrom = config.customTypeParams.fromDriver;
      }
      getSQLType() {
        return this.sqlName;
      }
      mapFromDriverValue(value) {
        return typeof this.mapFrom === "function" ? this.mapFrom(value) : value;
      }
      mapToDriverValue(value) {
        return typeof this.mapTo === "function" ? this.mapTo(value) : value;
      }
    };
    __publicField(SingleStoreCustomColumn, _a362, "SingleStoreCustomColumn");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/date.js
function date3(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config?.mode === "string") {
    return new SingleStoreDateStringBuilder(name2);
  }
  return new SingleStoreDateBuilder(name2);
}
var _a363, _b266, SingleStoreDateBuilder, _a364, _b267, SingleStoreDate, _a365, _b268, SingleStoreDateStringBuilder, _a366, _b269, SingleStoreDateString;
var init_date3 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/date.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreDateBuilder = class extends (_b266 = SingleStoreColumnBuilder, _a363 = entityKind, _b266) {
      constructor(name2) {
        super(name2, "date", "SingleStoreDate");
      }
      /** @internal */
      build(table6) {
        return new SingleStoreDate(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreDateBuilder, _a363, "SingleStoreDateBuilder");
    SingleStoreDate = class extends (_b267 = SingleStoreColumn, _a364 = entityKind, _b267) {
      constructor(table6, config) {
        super(table6, config);
      }
      getSQLType() {
        return `date`;
      }
      mapFromDriverValue(value) {
        return new Date(value);
      }
    };
    __publicField(SingleStoreDate, _a364, "SingleStoreDate");
    SingleStoreDateStringBuilder = class extends (_b268 = SingleStoreColumnBuilder, _a365 = entityKind, _b268) {
      constructor(name2) {
        super(name2, "string", "SingleStoreDateString");
      }
      /** @internal */
      build(table6) {
        return new SingleStoreDateString(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreDateStringBuilder, _a365, "SingleStoreDateStringBuilder");
    SingleStoreDateString = class extends (_b269 = SingleStoreColumn, _a366 = entityKind, _b269) {
      constructor(table6, config) {
        super(table6, config);
      }
      getSQLType() {
        return `date`;
      }
    };
    __publicField(SingleStoreDateString, _a366, "SingleStoreDateString");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/datetime.js
function datetime2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config?.mode === "string") {
    return new SingleStoreDateTimeStringBuilder(name2);
  }
  return new SingleStoreDateTimeBuilder(name2);
}
var _a367, _b270, SingleStoreDateTimeBuilder, _a368, _b271, SingleStoreDateTime, _a369, _b272, SingleStoreDateTimeStringBuilder, _a370, _b273, SingleStoreDateTimeString;
var init_datetime2 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/datetime.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreDateTimeBuilder = class extends (_b270 = SingleStoreColumnBuilder, _a367 = entityKind, _b270) {
      /** @internal */
      // TODO: we need to add a proper support for SingleStore
      generatedAlwaysAs(_as, _config) {
        throw new Error("Method not implemented.");
      }
      constructor(name2) {
        super(name2, "date", "SingleStoreDateTime");
      }
      /** @internal */
      build(table6) {
        return new SingleStoreDateTime(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreDateTimeBuilder, _a367, "SingleStoreDateTimeBuilder");
    SingleStoreDateTime = class extends (_b271 = SingleStoreColumn, _a368 = entityKind, _b271) {
      constructor(table6, config) {
        super(table6, config);
      }
      getSQLType() {
        return `datetime`;
      }
      mapToDriverValue(value) {
        return value.toISOString().replace("T", " ").replace("Z", "");
      }
      mapFromDriverValue(value) {
        return /* @__PURE__ */ new Date(value.replace(" ", "T") + "Z");
      }
    };
    __publicField(SingleStoreDateTime, _a368, "SingleStoreDateTime");
    SingleStoreDateTimeStringBuilder = class extends (_b272 = SingleStoreColumnBuilder, _a369 = entityKind, _b272) {
      /** @internal */
      // TODO: we need to add a proper support for SingleStore
      generatedAlwaysAs(_as, _config) {
        throw new Error("Method not implemented.");
      }
      constructor(name2) {
        super(name2, "string", "SingleStoreDateTimeString");
      }
      /** @internal */
      build(table6) {
        return new SingleStoreDateTimeString(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreDateTimeStringBuilder, _a369, "SingleStoreDateTimeStringBuilder");
    SingleStoreDateTimeString = class extends (_b273 = SingleStoreColumn, _a370 = entityKind, _b273) {
      constructor(table6, config) {
        super(table6, config);
      }
      getSQLType() {
        return `datetime`;
      }
    };
    __publicField(SingleStoreDateTimeString, _a370, "SingleStoreDateTimeString");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/decimal.js
function decimal2(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  const mode = config?.mode;
  return mode === "number" ? new SingleStoreDecimalNumberBuilder(name2, config) : mode === "bigint" ? new SingleStoreDecimalBigIntBuilder(name2, config) : new SingleStoreDecimalBuilder(name2, config);
}
var _a371, _b274, SingleStoreDecimalBuilder, _a372, _b275, SingleStoreDecimal, _a373, _b276, SingleStoreDecimalNumberBuilder, _a374, _b277, SingleStoreDecimalNumber, _a375, _b278, SingleStoreDecimalBigIntBuilder, _a376, _b279, SingleStoreDecimalBigInt;
var init_decimal2 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/decimal.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreDecimalBuilder = class extends (_b274 = SingleStoreColumnBuilderWithAutoIncrement, _a371 = entityKind, _b274) {
      constructor(name2, config) {
        super(name2, "string", "SingleStoreDecimal");
        this.config.precision = config?.precision;
        this.config.scale = config?.scale;
        this.config.unsigned = config?.unsigned;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreDecimal(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreDecimalBuilder, _a371, "SingleStoreDecimalBuilder");
    SingleStoreDecimal = class extends (_b275 = SingleStoreColumnWithAutoIncrement, _a372 = entityKind, _b275) {
      constructor() {
        super(...arguments);
        __publicField(this, "precision", this.config.precision);
        __publicField(this, "scale", this.config.scale);
        __publicField(this, "unsigned", this.config.unsigned);
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") return value;
        return String(value);
      }
      getSQLType() {
        let type = "";
        if (this.precision !== void 0 && this.scale !== void 0) {
          type += `decimal(${this.precision},${this.scale})`;
        } else if (this.precision === void 0) {
          type += "decimal";
        } else {
          type += `decimal(${this.precision})`;
        }
        type = type === "decimal(10,0)" || type === "decimal(10)" ? "decimal" : type;
        return this.unsigned ? `${type} unsigned` : type;
      }
    };
    __publicField(SingleStoreDecimal, _a372, "SingleStoreDecimal");
    SingleStoreDecimalNumberBuilder = class extends (_b276 = SingleStoreColumnBuilderWithAutoIncrement, _a373 = entityKind, _b276) {
      constructor(name2, config) {
        super(name2, "number", "SingleStoreDecimalNumber");
        this.config.precision = config?.precision;
        this.config.scale = config?.scale;
        this.config.unsigned = config?.unsigned;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreDecimalNumber(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreDecimalNumberBuilder, _a373, "SingleStoreDecimalNumberBuilder");
    SingleStoreDecimalNumber = class extends (_b277 = SingleStoreColumnWithAutoIncrement, _a374 = entityKind, _b277) {
      constructor() {
        super(...arguments);
        __publicField(this, "precision", this.config.precision);
        __publicField(this, "scale", this.config.scale);
        __publicField(this, "unsigned", this.config.unsigned);
        __publicField(this, "mapToDriverValue", String);
      }
      mapFromDriverValue(value) {
        if (typeof value === "number") return value;
        return Number(value);
      }
      getSQLType() {
        let type = "";
        if (this.precision !== void 0 && this.scale !== void 0) {
          type += `decimal(${this.precision},${this.scale})`;
        } else if (this.precision === void 0) {
          type += "decimal";
        } else {
          type += `decimal(${this.precision})`;
        }
        type = type === "decimal(10,0)" || type === "decimal(10)" ? "decimal" : type;
        return this.unsigned ? `${type} unsigned` : type;
      }
    };
    __publicField(SingleStoreDecimalNumber, _a374, "SingleStoreDecimalNumber");
    SingleStoreDecimalBigIntBuilder = class extends (_b278 = SingleStoreColumnBuilderWithAutoIncrement, _a375 = entityKind, _b278) {
      constructor(name2, config) {
        super(name2, "bigint", "SingleStoreDecimalBigInt");
        this.config.precision = config?.precision;
        this.config.scale = config?.scale;
        this.config.unsigned = config?.unsigned;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreDecimalBigInt(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreDecimalBigIntBuilder, _a375, "SingleStoreDecimalBigIntBuilder");
    SingleStoreDecimalBigInt = class extends (_b279 = SingleStoreColumnWithAutoIncrement, _a376 = entityKind, _b279) {
      constructor() {
        super(...arguments);
        __publicField(this, "precision", this.config.precision);
        __publicField(this, "scale", this.config.scale);
        __publicField(this, "unsigned", this.config.unsigned);
        __publicField(this, "mapFromDriverValue", BigInt);
        __publicField(this, "mapToDriverValue", String);
      }
      getSQLType() {
        let type = "";
        if (this.precision !== void 0 && this.scale !== void 0) {
          type += `decimal(${this.precision},${this.scale})`;
        } else if (this.precision === void 0) {
          type += "decimal";
        } else {
          type += `decimal(${this.precision})`;
        }
        type = type === "decimal(10,0)" || type === "decimal(10)" ? "decimal" : type;
        return this.unsigned ? `${type} unsigned` : type;
      }
    };
    __publicField(SingleStoreDecimalBigInt, _a376, "SingleStoreDecimalBigInt");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/double.js
function double2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new SingleStoreDoubleBuilder(name2, config);
}
var _a377, _b280, SingleStoreDoubleBuilder, _a378, _b281, SingleStoreDouble;
var init_double2 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/double.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreDoubleBuilder = class extends (_b280 = SingleStoreColumnBuilderWithAutoIncrement, _a377 = entityKind, _b280) {
      constructor(name2, config) {
        super(name2, "number", "SingleStoreDouble");
        this.config.precision = config?.precision;
        this.config.scale = config?.scale;
        this.config.unsigned = config?.unsigned;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreDouble(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreDoubleBuilder, _a377, "SingleStoreDoubleBuilder");
    SingleStoreDouble = class extends (_b281 = SingleStoreColumnWithAutoIncrement, _a378 = entityKind, _b281) {
      constructor() {
        super(...arguments);
        __publicField(this, "precision", this.config.precision);
        __publicField(this, "scale", this.config.scale);
        __publicField(this, "unsigned", this.config.unsigned);
      }
      getSQLType() {
        let type = "";
        if (this.precision !== void 0 && this.scale !== void 0) {
          type += `double(${this.precision},${this.scale})`;
        } else if (this.precision === void 0) {
          type += "double";
        } else {
          type += `double(${this.precision})`;
        }
        return this.unsigned ? `${type} unsigned` : type;
      }
    };
    __publicField(SingleStoreDouble, _a378, "SingleStoreDouble");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/enum.js
function singlestoreEnum(a, b) {
  const { name: name2, config: values } = getColumnNameAndConfig(a, b);
  if (values.length === 0) {
    throw new Error(`You have an empty array for "${name2}" enum values`);
  }
  return new SingleStoreEnumColumnBuilder(name2, values);
}
var _a379, _b282, SingleStoreEnumColumnBuilder, _a380, _b283, SingleStoreEnumColumn;
var init_enum3 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/enum.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreEnumColumnBuilder = class extends (_b282 = SingleStoreColumnBuilder, _a379 = entityKind, _b282) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      generatedAlwaysAs(as, config) {
        throw new Error("Method not implemented.");
      }
      constructor(name2, values) {
        super(name2, "string", "SingleStoreEnumColumn");
        this.config.enumValues = values;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreEnumColumn(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreEnumColumnBuilder, _a379, "SingleStoreEnumColumnBuilder");
    SingleStoreEnumColumn = class extends (_b283 = SingleStoreColumn, _a380 = entityKind, _b283) {
      constructor() {
        super(...arguments);
        __publicField(this, "enumValues", this.config.enumValues);
      }
      getSQLType() {
        return `enum(${this.enumValues.map((value) => `'${value}'`).join(",")})`;
      }
    };
    __publicField(SingleStoreEnumColumn, _a380, "SingleStoreEnumColumn");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/float.js
function float2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new SingleStoreFloatBuilder(name2, config);
}
var _a381, _b284, SingleStoreFloatBuilder, _a382, _b285, SingleStoreFloat;
var init_float2 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/float.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreFloatBuilder = class extends (_b284 = SingleStoreColumnBuilderWithAutoIncrement, _a381 = entityKind, _b284) {
      constructor(name2, config) {
        super(name2, "number", "SingleStoreFloat");
        this.config.precision = config?.precision;
        this.config.scale = config?.scale;
        this.config.unsigned = config?.unsigned;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreFloat(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreFloatBuilder, _a381, "SingleStoreFloatBuilder");
    SingleStoreFloat = class extends (_b285 = SingleStoreColumnWithAutoIncrement, _a382 = entityKind, _b285) {
      constructor() {
        super(...arguments);
        __publicField(this, "precision", this.config.precision);
        __publicField(this, "scale", this.config.scale);
        __publicField(this, "unsigned", this.config.unsigned);
      }
      getSQLType() {
        let type = "";
        if (this.precision !== void 0 && this.scale !== void 0) {
          type += `float(${this.precision},${this.scale})`;
        } else if (this.precision === void 0) {
          type += "float";
        } else {
          type += `float(${this.precision},0)`;
        }
        return this.unsigned ? `${type} unsigned` : type;
      }
    };
    __publicField(SingleStoreFloat, _a382, "SingleStoreFloat");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/int.js
function int2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new SingleStoreIntBuilder(name2, config);
}
var _a383, _b286, SingleStoreIntBuilder, _a384, _b287, SingleStoreInt;
var init_int2 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/int.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreIntBuilder = class extends (_b286 = SingleStoreColumnBuilderWithAutoIncrement, _a383 = entityKind, _b286) {
      constructor(name2, config) {
        super(name2, "number", "SingleStoreInt");
        this.config.unsigned = config ? config.unsigned : false;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreInt(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreIntBuilder, _a383, "SingleStoreIntBuilder");
    SingleStoreInt = class extends (_b287 = SingleStoreColumnWithAutoIncrement, _a384 = entityKind, _b287) {
      getSQLType() {
        return `int${this.config.unsigned ? " unsigned" : ""}`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number(value);
        }
        return value;
      }
    };
    __publicField(SingleStoreInt, _a384, "SingleStoreInt");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/json.js
function json3(name2) {
  return new SingleStoreJsonBuilder(name2 ?? "");
}
var _a385, _b288, SingleStoreJsonBuilder, _a386, _b289, SingleStoreJson;
var init_json3 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/json.js"() {
    "use strict";
    init_entity();
    init_common5();
    SingleStoreJsonBuilder = class extends (_b288 = SingleStoreColumnBuilder, _a385 = entityKind, _b288) {
      constructor(name2) {
        super(name2, "json", "SingleStoreJson");
      }
      /** @internal */
      build(table6) {
        return new SingleStoreJson(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreJsonBuilder, _a385, "SingleStoreJsonBuilder");
    SingleStoreJson = class extends (_b289 = SingleStoreColumn, _a386 = entityKind, _b289) {
      getSQLType() {
        return "json";
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
    };
    __publicField(SingleStoreJson, _a386, "SingleStoreJson");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/mediumint.js
function mediumint2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new SingleStoreMediumIntBuilder(name2, config);
}
var _a387, _b290, SingleStoreMediumIntBuilder, _a388, _b291, SingleStoreMediumInt;
var init_mediumint2 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/mediumint.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreMediumIntBuilder = class extends (_b290 = SingleStoreColumnBuilderWithAutoIncrement, _a387 = entityKind, _b290) {
      constructor(name2, config) {
        super(name2, "number", "SingleStoreMediumInt");
        this.config.unsigned = config ? config.unsigned : false;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreMediumInt(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreMediumIntBuilder, _a387, "SingleStoreMediumIntBuilder");
    SingleStoreMediumInt = class extends (_b291 = SingleStoreColumnWithAutoIncrement, _a388 = entityKind, _b291) {
      getSQLType() {
        return `mediumint${this.config.unsigned ? " unsigned" : ""}`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number(value);
        }
        return value;
      }
    };
    __publicField(SingleStoreMediumInt, _a388, "SingleStoreMediumInt");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/real.js
function real4(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new SingleStoreRealBuilder(name2, config);
}
var _a389, _b292, SingleStoreRealBuilder, _a390, _b293, SingleStoreReal;
var init_real4 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/real.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreRealBuilder = class extends (_b292 = SingleStoreColumnBuilderWithAutoIncrement, _a389 = entityKind, _b292) {
      constructor(name2, config) {
        super(name2, "number", "SingleStoreReal");
        this.config.precision = config?.precision;
        this.config.scale = config?.scale;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreReal(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreRealBuilder, _a389, "SingleStoreRealBuilder");
    SingleStoreReal = class extends (_b293 = SingleStoreColumnWithAutoIncrement, _a390 = entityKind, _b293) {
      constructor() {
        super(...arguments);
        __publicField(this, "precision", this.config.precision);
        __publicField(this, "scale", this.config.scale);
      }
      getSQLType() {
        if (this.precision !== void 0 && this.scale !== void 0) {
          return `real(${this.precision}, ${this.scale})`;
        } else if (this.precision === void 0) {
          return "real";
        } else {
          return `real(${this.precision})`;
        }
      }
    };
    __publicField(SingleStoreReal, _a390, "SingleStoreReal");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/serial.js
function serial3(name2) {
  return new SingleStoreSerialBuilder(name2 ?? "");
}
var _a391, _b294, SingleStoreSerialBuilder, _a392, _b295, SingleStoreSerial;
var init_serial3 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/serial.js"() {
    "use strict";
    init_entity();
    init_common5();
    SingleStoreSerialBuilder = class extends (_b294 = SingleStoreColumnBuilderWithAutoIncrement, _a391 = entityKind, _b294) {
      constructor(name2) {
        super(name2, "number", "SingleStoreSerial");
        this.config.hasDefault = true;
        this.config.autoIncrement = true;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreSerial(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreSerialBuilder, _a391, "SingleStoreSerialBuilder");
    SingleStoreSerial = class extends (_b295 = SingleStoreColumnWithAutoIncrement, _a392 = entityKind, _b295) {
      getSQLType() {
        return "serial";
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number(value);
        }
        return value;
      }
    };
    __publicField(SingleStoreSerial, _a392, "SingleStoreSerial");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/smallint.js
function smallint3(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new SingleStoreSmallIntBuilder(name2, config);
}
var _a393, _b296, SingleStoreSmallIntBuilder, _a394, _b297, SingleStoreSmallInt;
var init_smallint3 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/smallint.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreSmallIntBuilder = class extends (_b296 = SingleStoreColumnBuilderWithAutoIncrement, _a393 = entityKind, _b296) {
      constructor(name2, config) {
        super(name2, "number", "SingleStoreSmallInt");
        this.config.unsigned = config ? config.unsigned : false;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreSmallInt(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreSmallIntBuilder, _a393, "SingleStoreSmallIntBuilder");
    SingleStoreSmallInt = class extends (_b297 = SingleStoreColumnWithAutoIncrement, _a394 = entityKind, _b297) {
      getSQLType() {
        return `smallint${this.config.unsigned ? " unsigned" : ""}`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number(value);
        }
        return value;
      }
    };
    __publicField(SingleStoreSmallInt, _a394, "SingleStoreSmallInt");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/text.js
function text4(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new SingleStoreTextBuilder(name2, "text", config);
}
function tinytext2(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new SingleStoreTextBuilder(name2, "tinytext", config);
}
function mediumtext2(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new SingleStoreTextBuilder(name2, "mediumtext", config);
}
function longtext2(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new SingleStoreTextBuilder(name2, "longtext", config);
}
var _a395, _b298, SingleStoreTextBuilder, _a396, _b299, SingleStoreText;
var init_text4 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/text.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreTextBuilder = class extends (_b298 = SingleStoreColumnBuilder, _a395 = entityKind, _b298) {
      constructor(name2, textType, config) {
        super(name2, "string", "SingleStoreText");
        this.config.textType = textType;
        this.config.enumValues = config.enum;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreText(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreTextBuilder, _a395, "SingleStoreTextBuilder");
    SingleStoreText = class extends (_b299 = SingleStoreColumn, _a396 = entityKind, _b299) {
      constructor() {
        super(...arguments);
        __publicField(this, "textType", this.config.textType);
        __publicField(this, "enumValues", this.config.enumValues);
      }
      getSQLType() {
        return this.textType;
      }
    };
    __publicField(SingleStoreText, _a396, "SingleStoreText");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/time.js
function time3(name2) {
  return new SingleStoreTimeBuilder(name2 ?? "");
}
var _a397, _b300, SingleStoreTimeBuilder, _a398, _b301, SingleStoreTime;
var init_time3 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/time.js"() {
    "use strict";
    init_entity();
    init_common5();
    SingleStoreTimeBuilder = class extends (_b300 = SingleStoreColumnBuilder, _a397 = entityKind, _b300) {
      constructor(name2) {
        super(name2, "string", "SingleStoreTime");
      }
      /** @internal */
      build(table6) {
        return new SingleStoreTime(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreTimeBuilder, _a397, "SingleStoreTimeBuilder");
    SingleStoreTime = class extends (_b301 = SingleStoreColumn, _a398 = entityKind, _b301) {
      getSQLType() {
        return `time`;
      }
    };
    __publicField(SingleStoreTime, _a398, "SingleStoreTime");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/date.common.js
var _a399, _b302, SingleStoreDateColumnBaseBuilder, _a400, _b303, SingleStoreDateBaseColumn;
var init_date_common3 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/date.common.js"() {
    "use strict";
    init_entity();
    init_sql();
    init_common5();
    SingleStoreDateColumnBaseBuilder = class extends (_b302 = SingleStoreColumnBuilder, _a399 = entityKind, _b302) {
      defaultNow() {
        return this.default(sql`now()`);
      }
      onUpdateNow() {
        this.config.hasOnUpdateNow = true;
        this.config.hasDefault = true;
        return this;
      }
    };
    __publicField(SingleStoreDateColumnBaseBuilder, _a399, "SingleStoreDateColumnBuilder");
    SingleStoreDateBaseColumn = class extends (_b303 = SingleStoreColumn, _a400 = entityKind, _b303) {
      constructor() {
        super(...arguments);
        __publicField(this, "hasOnUpdateNow", this.config.hasOnUpdateNow);
      }
    };
    __publicField(SingleStoreDateBaseColumn, _a400, "SingleStoreDateColumn");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/timestamp.js
function timestamp3(a, b = {}) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  if (config?.mode === "string") {
    return new SingleStoreTimestampStringBuilder(name2);
  }
  return new SingleStoreTimestampBuilder(name2);
}
var _a401, _b304, SingleStoreTimestampBuilder, _a402, _b305, SingleStoreTimestamp, _a403, _b306, SingleStoreTimestampStringBuilder, _a404, _b307, SingleStoreTimestampString;
var init_timestamp3 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/timestamp.js"() {
    "use strict";
    init_entity();
    init_sql();
    init_utils2();
    init_date_common3();
    SingleStoreTimestampBuilder = class extends (_b304 = SingleStoreDateColumnBaseBuilder, _a401 = entityKind, _b304) {
      constructor(name2) {
        super(name2, "date", "SingleStoreTimestamp");
      }
      /** @internal */
      build(table6) {
        return new SingleStoreTimestamp(
          table6,
          this.config
        );
      }
      defaultNow() {
        return this.default(sql`CURRENT_TIMESTAMP`);
      }
    };
    __publicField(SingleStoreTimestampBuilder, _a401, "SingleStoreTimestampBuilder");
    SingleStoreTimestamp = class extends (_b305 = SingleStoreDateBaseColumn, _a402 = entityKind, _b305) {
      getSQLType() {
        return `timestamp`;
      }
      mapFromDriverValue(value) {
        return /* @__PURE__ */ new Date(value + "+0000");
      }
      mapToDriverValue(value) {
        return value.toISOString().slice(0, -1).replace("T", " ");
      }
    };
    __publicField(SingleStoreTimestamp, _a402, "SingleStoreTimestamp");
    SingleStoreTimestampStringBuilder = class extends (_b306 = SingleStoreDateColumnBaseBuilder, _a403 = entityKind, _b306) {
      constructor(name2) {
        super(name2, "string", "SingleStoreTimestampString");
      }
      /** @internal */
      build(table6) {
        return new SingleStoreTimestampString(
          table6,
          this.config
        );
      }
      defaultNow() {
        return this.default(sql`CURRENT_TIMESTAMP`);
      }
    };
    __publicField(SingleStoreTimestampStringBuilder, _a403, "SingleStoreTimestampStringBuilder");
    SingleStoreTimestampString = class extends (_b307 = SingleStoreDateBaseColumn, _a404 = entityKind, _b307) {
      getSQLType() {
        return `timestamp`;
      }
    };
    __publicField(SingleStoreTimestampString, _a404, "SingleStoreTimestampString");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/tinyint.js
function tinyint2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new SingleStoreTinyIntBuilder(name2, config);
}
var _a405, _b308, SingleStoreTinyIntBuilder, _a406, _b309, SingleStoreTinyInt;
var init_tinyint2 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/tinyint.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreTinyIntBuilder = class extends (_b308 = SingleStoreColumnBuilderWithAutoIncrement, _a405 = entityKind, _b308) {
      constructor(name2, config) {
        super(name2, "number", "SingleStoreTinyInt");
        this.config.unsigned = config ? config.unsigned : false;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreTinyInt(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreTinyIntBuilder, _a405, "SingleStoreTinyIntBuilder");
    SingleStoreTinyInt = class extends (_b309 = SingleStoreColumnWithAutoIncrement, _a406 = entityKind, _b309) {
      getSQLType() {
        return `tinyint${this.config.unsigned ? " unsigned" : ""}`;
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") {
          return Number(value);
        }
        return value;
      }
    };
    __publicField(SingleStoreTinyInt, _a406, "SingleStoreTinyInt");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/varbinary.js
function varbinary2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new SingleStoreVarBinaryBuilder(name2, config);
}
var _a407, _b310, SingleStoreVarBinaryBuilder, _a408, _b311, SingleStoreVarBinary;
var init_varbinary2 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/varbinary.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreVarBinaryBuilder = class extends (_b310 = SingleStoreColumnBuilder, _a407 = entityKind, _b310) {
      /** @internal */
      constructor(name2, config) {
        super(name2, "string", "SingleStoreVarBinary");
        this.config.length = config?.length;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreVarBinary(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreVarBinaryBuilder, _a407, "SingleStoreVarBinaryBuilder");
    SingleStoreVarBinary = class extends (_b311 = SingleStoreColumn, _a408 = entityKind, _b311) {
      constructor() {
        super(...arguments);
        __publicField(this, "length", this.config.length);
      }
      mapFromDriverValue(value) {
        if (typeof value === "string") return value;
        if (Buffer.isBuffer(value)) return value.toString();
        const str = [];
        for (const v of value) {
          str.push(v === 49 ? "1" : "0");
        }
        return str.join("");
      }
      getSQLType() {
        return this.length === void 0 ? `varbinary` : `varbinary(${this.length})`;
      }
    };
    __publicField(SingleStoreVarBinary, _a408, "SingleStoreVarBinary");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/varchar.js
function varchar3(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new SingleStoreVarCharBuilder(name2, config);
}
var _a409, _b312, SingleStoreVarCharBuilder, _a410, _b313, SingleStoreVarChar;
var init_varchar3 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/varchar.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreVarCharBuilder = class extends (_b312 = SingleStoreColumnBuilder, _a409 = entityKind, _b312) {
      /** @internal */
      constructor(name2, config) {
        super(name2, "string", "SingleStoreVarChar");
        this.config.length = config.length;
        this.config.enum = config.enum;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreVarChar(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreVarCharBuilder, _a409, "SingleStoreVarCharBuilder");
    SingleStoreVarChar = class extends (_b313 = SingleStoreColumn, _a410 = entityKind, _b313) {
      constructor() {
        super(...arguments);
        __publicField(this, "length", this.config.length);
        __publicField(this, "enumValues", this.config.enum);
      }
      getSQLType() {
        return this.length === void 0 ? `varchar` : `varchar(${this.length})`;
      }
    };
    __publicField(SingleStoreVarChar, _a410, "SingleStoreVarChar");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/vector.js
function vector2(a, b) {
  const { name: name2, config } = getColumnNameAndConfig(a, b);
  return new SingleStoreVectorBuilder(name2, config);
}
var _a411, _b314, SingleStoreVectorBuilder, _a412, _b315, SingleStoreVector;
var init_vector4 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/vector.js"() {
    "use strict";
    init_entity();
    init_utils2();
    init_common5();
    SingleStoreVectorBuilder = class extends (_b314 = SingleStoreColumnBuilder, _a411 = entityKind, _b314) {
      constructor(name2, config) {
        super(name2, "array", "SingleStoreVector");
        this.config.dimensions = config.dimensions;
        this.config.elementType = config.elementType;
      }
      /** @internal */
      build(table6) {
        return new SingleStoreVector(
          table6,
          this.config
        );
      }
      /** @internal */
      generatedAlwaysAs(as, config) {
        throw new Error("not implemented");
      }
    };
    __publicField(SingleStoreVectorBuilder, _a411, "SingleStoreVectorBuilder");
    SingleStoreVector = class extends (_b315 = SingleStoreColumn, _a412 = entityKind, _b315) {
      constructor() {
        super(...arguments);
        __publicField(this, "dimensions", this.config.dimensions);
        __publicField(this, "elementType", this.config.elementType);
      }
      getSQLType() {
        return `vector(${this.dimensions}, ${this.elementType || "F32"})`;
      }
      mapToDriverValue(value) {
        return JSON.stringify(value);
      }
      mapFromDriverValue(value) {
        return JSON.parse(value);
      }
    };
    __publicField(SingleStoreVector, _a412, "SingleStoreVector");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/year.js
function year2(name2) {
  return new SingleStoreYearBuilder(name2 ?? "");
}
var _a413, _b316, SingleStoreYearBuilder, _a414, _b317, SingleStoreYear;
var init_year2 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/year.js"() {
    "use strict";
    init_entity();
    init_common5();
    SingleStoreYearBuilder = class extends (_b316 = SingleStoreColumnBuilder, _a413 = entityKind, _b316) {
      constructor(name2) {
        super(name2, "number", "SingleStoreYear");
      }
      /** @internal */
      build(table6) {
        return new SingleStoreYear(
          table6,
          this.config
        );
      }
    };
    __publicField(SingleStoreYearBuilder, _a413, "SingleStoreYearBuilder");
    SingleStoreYear = class extends (_b317 = SingleStoreColumn, _a414 = entityKind, _b317) {
      getSQLType() {
        return `year`;
      }
    };
    __publicField(SingleStoreYear, _a414, "SingleStoreYear");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/index.js
var init_columns4 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/index.js"() {
    "use strict";
    init_bigint3();
    init_binary2();
    init_boolean3();
    init_char3();
    init_common5();
    init_custom4();
    init_date3();
    init_datetime2();
    init_decimal2();
    init_double2();
    init_enum3();
    init_float2();
    init_int2();
    init_json3();
    init_mediumint2();
    init_real4();
    init_serial3();
    init_smallint3();
    init_text4();
    init_time3();
    init_timestamp3();
    init_tinyint2();
    init_varbinary2();
    init_varchar3();
    init_vector4();
    init_year2();
  }
});

// ../drizzle-orm/dist/singlestore-core/query-builders/count.js
var _a415, _b318, _c12, _SingleStoreCountBuilder, SingleStoreCountBuilder;
var init_count4 = __esm({
  "../drizzle-orm/dist/singlestore-core/query-builders/count.js"() {
    "use strict";
    init_entity();
    init_sql();
    _SingleStoreCountBuilder = class _SingleStoreCountBuilder extends (_c12 = SQL, _b318 = entityKind, _a415 = Symbol.toStringTag, _c12) {
      constructor(params) {
        super(_SingleStoreCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks);
        __publicField(this, "sql");
        __publicField(this, _a415, "SingleStoreCountBuilder");
        __publicField(this, "session");
        this.params = params;
        this.mapWith(Number);
        this.session = params.session;
        this.sql = _SingleStoreCountBuilder.buildCount(
          params.source,
          params.filters
        );
      }
      static buildEmbeddedCount(source, filters) {
        return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`;
      }
      static buildCount(source, filters) {
        return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters}`;
      }
      then(onfulfilled, onrejected) {
        return Promise.resolve(this.session.count(this.sql)).then(
          onfulfilled,
          onrejected
        );
      }
      catch(onRejected) {
        return this.then(void 0, onRejected);
      }
      finally(onFinally) {
        return this.then(
          (value) => {
            onFinally?.();
            return value;
          },
          (reason) => {
            onFinally?.();
            throw reason;
          }
        );
      }
    };
    __publicField(_SingleStoreCountBuilder, _b318, "SingleStoreCountBuilder");
    SingleStoreCountBuilder = _SingleStoreCountBuilder;
  }
});

// ../drizzle-orm/dist/singlestore-core/indexes.js
var _a416, IndexBuilderOn4, _a417, IndexBuilder4, _a418, Index6;
var init_indexes4 = __esm({
  "../drizzle-orm/dist/singlestore-core/indexes.js"() {
    "use strict";
    init_entity();
    _a416 = entityKind;
    IndexBuilderOn4 = class {
      constructor(name2, unique) {
        this.name = name2;
        this.unique = unique;
      }
      on(...columns) {
        return new IndexBuilder4(this.name, columns, this.unique);
      }
    };
    __publicField(IndexBuilderOn4, _a416, "SingleStoreIndexBuilderOn");
    _a417 = entityKind;
    IndexBuilder4 = class {
      constructor(name2, columns, unique) {
        /** @internal */
        __publicField(this, "config");
        this.config = {
          name: name2,
          columns,
          unique
        };
      }
      using(using) {
        this.config.using = using;
        return this;
      }
      algorythm(algorythm) {
        this.config.algorythm = algorythm;
        return this;
      }
      lock(lock) {
        this.config.lock = lock;
        return this;
      }
      /** @internal */
      build(table6) {
        return new Index6(this.config, table6);
      }
    };
    __publicField(IndexBuilder4, _a417, "SingleStoreIndexBuilder");
    _a418 = entityKind;
    Index6 = class {
      constructor(config, table6) {
        __publicField(this, "config");
        this.config = { ...config, table: table6 };
      }
    };
    __publicField(Index6, _a418, "SingleStoreIndex");
  }
});

// ../drizzle-orm/dist/singlestore-core/columns/all.js
function getSingleStoreColumnBuilders() {
  return {
    bigint: bigint3,
    binary: binary2,
    boolean: boolean3,
    char: char3,
    customType: customType4,
    date: date3,
    datetime: datetime2,
    decimal: decimal2,
    double: double2,
    singlestoreEnum,
    float: float2,
    int: int2,
    json: json3,
    mediumint: mediumint2,
    real: real4,
    serial: serial3,
    smallint: smallint3,
    longtext: longtext2,
    mediumtext: mediumtext2,
    text: text4,
    tinytext: tinytext2,
    time: time3,
    timestamp: timestamp3,
    tinyint: tinyint2,
    varbinary: varbinary2,
    varchar: varchar3,
    vector: vector2,
    year: year2
  };
}
var init_all4 = __esm({
  "../drizzle-orm/dist/singlestore-core/columns/all.js"() {
    "use strict";
    init_bigint3();
    init_binary2();
    init_boolean3();
    init_char3();
    init_custom4();
    init_date3();
    init_datetime2();
    init_decimal2();
    init_double2();
    init_enum3();
    init_float2();
    init_int2();
    init_json3();
    init_mediumint2();
    init_real4();
    init_serial3();
    init_smallint3();
    init_text4();
    init_time3();
    init_timestamp3();
    init_tinyint2();
    init_varbinary2();
    init_varchar3();
    init_vector4();
    init_year2();
  }
});

// ../drizzle-orm/dist/singlestore-core/table.js
function singlestoreTableWithSchema(name2, columns, extraConfig, schema5, baseName = name2) {
  const rawTable = new SingleStoreTable(name2, schema5, baseName);
  const parsedColumns = typeof columns === "function" ? columns(getSingleStoreColumnBuilders()) : columns;
  const builtColumns = Object.fromEntries(
    Object.entries(parsedColumns).map(([name22, colBuilderBase]) => {
      const colBuilder = colBuilderBase;
      colBuilder.setName(name22);
      const column6 = colBuilder.build(rawTable);
      return [name22, column6];
    })
  );
  const table6 = Object.assign(rawTable, builtColumns);
  table6[Table2.Symbol.Columns] = builtColumns;
  table6[Table2.Symbol.ExtraConfigColumns] = builtColumns;
  if (extraConfig) {
    table6[SingleStoreTable.Symbol.ExtraConfigBuilder] = extraConfig;
  }
  return table6;
}
var _a419, _b319, _c13, _d5, SingleStoreTable;
var init_table5 = __esm({
  "../drizzle-orm/dist/singlestore-core/table.js"() {
    "use strict";
    init_entity();
    init_table();
    init_all4();
    SingleStoreTable = class extends (_d5 = Table2, _c13 = entityKind, _b319 = Table2.Symbol.Columns, _a419 = Table2.Symbol.ExtraConfigBuilder, _d5) {
      constructor() {
        super(...arguments);
        /** @internal */
        __publicField(this, _b319);
        /** @internal */
        __publicField(this, _a419);
      }
    };
    __publicField(SingleStoreTable, _c13, "SingleStoreTable");
    /** @internal */
    __publicField(SingleStoreTable, "Symbol", Object.assign({}, Table2.Symbol, {}));
  }
});

// ../drizzle-orm/dist/singlestore-core/primary-keys.js
var _a420, PrimaryKeyBuilder4, _a421, PrimaryKey4;
var init_primary_keys4 = __esm({
  "../drizzle-orm/dist/singlestore-core/primary-keys.js"() {
    "use strict";
    init_entity();
    init_table5();
    _a420 = entityKind;
    PrimaryKeyBuilder4 = class {
      constructor(columns, name2) {
        /** @internal */
        __publicField(this, "columns");
        /** @internal */
        __publicField(this, "name");
        this.columns = columns;
        this.name = name2;
      }
      /** @internal */
      build(table6) {
        return new PrimaryKey4(table6, this.columns, this.name);
      }
    };
    __publicField(PrimaryKeyBuilder4, _a420, "SingleStorePrimaryKeyBuilder");
    _a421 = entityKind;
    PrimaryKey4 = class {
      constructor(table6, columns, name2) {
        __publicField(this, "columns");
        __publicField(this, "name");
        this.table = table6;
        this.columns = columns;
        this.name = name2;
      }
      getName() {
        return this.name ?? `${this.table[SingleStoreTable.Symbol.Name]}_${this.columns.map((column6) => column6.name).join("_")}_pk`;
      }
    };
    __publicField(PrimaryKey4, _a421, "SingleStorePrimaryKey");
  }
});

// ../drizzle-orm/dist/singlestore-core/utils.js
function extractUsedTable4(table6) {
  if (is(table6, SingleStoreTable)) {
    return [`${table6[Table2.Symbol.BaseName]}`];
  }
  if (is(table6, Subquery)) {
    return table6._.usedTables ?? [];
  }
  if (is(table6, SQL)) {
    return table6.usedTables ?? [];
  }
  return [];
}
function getTableConfig4(table6) {
  const columns = Object.values(table6[SingleStoreTable.Symbol.Columns]);
  const indexes = [];
  const primaryKeys = [];
  const uniqueConstraints = [];
  const name2 = table6[Table2.Symbol.Name];
  const schema5 = table6[Table2.Symbol.Schema];
  const baseName = table6[Table2.Symbol.BaseName];
  const extraConfigBuilder = table6[SingleStoreTable.Symbol.ExtraConfigBuilder];
  if (extraConfigBuilder !== void 0) {
    const extraConfig = extraConfigBuilder(table6[SingleStoreTable.Symbol.Columns]);
    const extraValues = Array.isArray(extraConfig) ? extraConfig.flat(1) : Object.values(extraConfig);
    for (const builder of Object.values(extraValues)) {
      if (is(builder, IndexBuilder4)) {
        indexes.push(builder.build(table6));
      } else if (is(builder, UniqueConstraintBuilder4)) {
        uniqueConstraints.push(builder.build(table6));
      } else if (is(builder, PrimaryKeyBuilder4)) {
        primaryKeys.push(builder.build(table6));
      }
    }
  }
  return {
    columns,
    indexes,
    primaryKeys,
    uniqueConstraints,
    name: name2,
    schema: schema5,
    baseName
  };
}
var init_utils10 = __esm({
  "../drizzle-orm/dist/singlestore-core/utils.js"() {
    "use strict";
    init_entity();
    init_sql();
    init_subquery();
    init_table();
    init_indexes4();
    init_primary_keys4();
    init_table5();
    init_unique_constraint4();
  }
});

// ../drizzle-orm/dist/singlestore-core/query-builders/delete.js
var _a422, _b320, SingleStoreDeleteBase;
var init_delete4 = __esm({
  "../drizzle-orm/dist/singlestore-core/query-builders/delete.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_selection_proxy();
    init_table();
    init_utils10();
    SingleStoreDeleteBase = class extends (_b320 = QueryPromise, _a422 = entityKind, _b320) {
      constructor(table6, session, dialect6, withList) {
        super();
        __publicField(this, "config");
        __publicField(this, "execute", (placeholderValues) => {
          return this.prepare().execute(placeholderValues);
        });
        __publicField(this, "createIterator", () => {
          const self2 = this;
          return async function* (placeholderValues) {
            yield* self2.prepare().iterator(placeholderValues);
          };
        });
        __publicField(this, "iterator", this.createIterator());
        this.table = table6;
        this.session = session;
        this.dialect = dialect6;
        this.config = { table: table6, withList };
      }
      /**
       * Adds a `where` clause to the query.
       *
       * Calling this method will delete only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/delete}
       *
       * @param where the `where` clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be deleted.
       *
       * ```ts
       * // Delete all cars with green color
       * db.delete(cars).where(eq(cars.color, 'green'));
       * // or
       * db.delete(cars).where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Delete all BMW cars with a green color
       * db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Delete all cars with the green or blue color
       * db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        this.config.where = where;
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.table[Table2.Symbol.Columns],
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          this.config.orderBy = orderByArray;
        } else {
          const orderByArray = columns;
          this.config.orderBy = orderByArray;
        }
        return this;
      }
      limit(limit) {
        this.config.limit = limit;
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildDeleteQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      prepare() {
        return this.session.prepareQuery(
          this.dialect.sqlToQuery(this.getSQL()),
          this.config.returning,
          void 0,
          void 0,
          void 0,
          {
            type: "delete",
            tables: extractUsedTable4(this.config.table)
          }
        );
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(SingleStoreDeleteBase, _a422, "SingleStoreDelete");
  }
});

// ../drizzle-orm/dist/singlestore-core/query-builders/insert.js
var _a423, SingleStoreInsertBuilder, _a424, _b321, SingleStoreInsertBase;
var init_insert4 = __esm({
  "../drizzle-orm/dist/singlestore-core/query-builders/insert.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_sql();
    init_table();
    init_utils2();
    init_utils10();
    _a423 = entityKind;
    SingleStoreInsertBuilder = class {
      constructor(table6, session, dialect6) {
        __publicField(this, "shouldIgnore", false);
        this.table = table6;
        this.session = session;
        this.dialect = dialect6;
      }
      ignore() {
        this.shouldIgnore = true;
        return this;
      }
      values(values) {
        values = Array.isArray(values) ? values : [values];
        if (values.length === 0) {
          throw new Error("values() must be called with at least one value");
        }
        const mappedValues = values.map((entry) => {
          const result = {};
          const cols = this.table[Table2.Symbol.Columns];
          for (const colKey of Object.keys(entry)) {
            const colValue = entry[colKey];
            result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);
          }
          return result;
        });
        return new SingleStoreInsertBase(this.table, mappedValues, this.shouldIgnore, this.session, this.dialect);
      }
    };
    __publicField(SingleStoreInsertBuilder, _a423, "SingleStoreInsertBuilder");
    SingleStoreInsertBase = class extends (_b321 = QueryPromise, _a424 = entityKind, _b321) {
      constructor(table6, values, ignore, session, dialect6) {
        super();
        __publicField(this, "config");
        __publicField(this, "execute", (placeholderValues) => {
          return this.prepare().execute(placeholderValues);
        });
        __publicField(this, "createIterator", () => {
          const self2 = this;
          return async function* (placeholderValues) {
            yield* self2.prepare().iterator(placeholderValues);
          };
        });
        __publicField(this, "iterator", this.createIterator());
        this.session = session;
        this.dialect = dialect6;
        this.config = { table: table6, values, ignore };
      }
      /**
       * Adds an `on duplicate key update` clause to the query.
       *
       * Calling this method will update update the row if any unique index conflicts. MySQL will automatically determine the conflict target based on the primary key and unique indexes.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert#on-duplicate-key-update}
       *
       * @param config The `set` clause
       *
       * @example
       * ```ts
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW'})
       *   .onDuplicateKeyUpdate({ set: { brand: 'Porsche' }});
       * ```
       *
       * While MySQL does not directly support doing nothing on conflict, you can perform a no-op by setting any column's value to itself and achieve the same effect:
       *
       * ```ts
       * import { sql } from 'drizzle-orm';
       *
       * await db.insert(cars)
       *   .values({ id: 1, brand: 'BMW' })
       *   .onDuplicateKeyUpdate({ set: { id: sql`id` } });
       * ```
       */
      onDuplicateKeyUpdate(config) {
        const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));
        this.config.onConflict = sql`update ${setSql}`;
        return this;
      }
      $returningId() {
        const returning = [];
        for (const [key, value] of Object.entries(this.config.table[Table2.Symbol.Columns])) {
          if (value.primary) {
            returning.push({ field: value, path: [key] });
          }
        }
        this.config.returning = orderSelectedFields(this.config.table[Table2.Symbol.Columns]);
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildInsertQuery(this.config).sql;
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      prepare() {
        const { sql: sql2, generatedIds } = this.dialect.buildInsertQuery(this.config);
        return this.session.prepareQuery(
          this.dialect.sqlToQuery(sql2),
          void 0,
          void 0,
          generatedIds,
          this.config.returning,
          {
            type: "delete",
            tables: extractUsedTable4(this.config.table)
          }
        );
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(SingleStoreInsertBase, _a424, "SingleStoreInsert");
  }
});

// ../drizzle-orm/dist/singlestore-core/dialect.js
var _a425, SingleStoreDialect;
var init_dialect4 = __esm({
  "../drizzle-orm/dist/singlestore-core/dialect.js"() {
    "use strict";
    init_alias();
    init_casing();
    init_column();
    init_entity();
    init_errors2();
    init_relations();
    init_expressions();
    init_sql();
    init_subquery();
    init_table();
    init_utils2();
    init_view_common();
    init_common5();
    init_table5();
    _a425 = entityKind;
    SingleStoreDialect = class {
      constructor(config) {
        /** @internal */
        __publicField(this, "casing");
        this.casing = new CasingCache(config?.casing);
      }
      async migrate(migrations, session, config) {
        const migrationsTable = config.migrationsTable ?? "__drizzle_migrations";
        const migrationTableCreate = sql`
			create table if not exists ${sql.identifier(migrationsTable)} (
				id serial primary key,
				hash text not null,
				created_at bigint
			)
		`;
        await session.execute(migrationTableCreate);
        const dbMigrations = await session.all(
          sql`select id, hash, created_at from ${sql.identifier(migrationsTable)} order by created_at desc limit 1`
        );
        const lastDbMigration = dbMigrations[0];
        await session.transaction(async (tx) => {
          for (const migration of migrations) {
            if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) {
              for (const stmt of migration.sql) {
                await tx.execute(sql.raw(stmt));
              }
              await tx.execute(
                sql`insert into ${sql.identifier(migrationsTable)} (\`hash\`, \`created_at\`) values(${migration.hash}, ${migration.folderMillis})`
              );
            }
          }
        });
      }
      escapeName(name2) {
        return `\`${name2}\``;
      }
      escapeParam(_num) {
        return `?`;
      }
      escapeString(str) {
        return `'${str.replace(/'/g, "''")}'`;
      }
      buildWithCTE(queries) {
        if (!queries?.length) return void 0;
        const withSqlChunks = [sql`with `];
        for (const [i, w] of queries.entries()) {
          withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);
          if (i < queries.length - 1) {
            withSqlChunks.push(sql`, `);
          }
        }
        withSqlChunks.push(sql` `);
        return sql.join(withSqlChunks);
      }
      buildDeleteQuery({ table: table6, where, returning, withList, limit, orderBy }) {
        const withSql = this.buildWithCTE(withList);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const whereSql = where ? sql` where ${where}` : void 0;
        const orderBySql = this.buildOrderBy(orderBy);
        const limitSql = this.buildLimit(limit);
        return sql`${withSql}delete from ${table6}${whereSql}${orderBySql}${limitSql}${returningSql}`;
      }
      buildUpdateSet(table6, set) {
        const tableColumns = table6[Table2.Symbol.Columns];
        const columnNames = Object.keys(tableColumns).filter(
          (colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0
        );
        const setSize = columnNames.length;
        return sql.join(columnNames.flatMap((colName, i) => {
          const col = tableColumns[colName];
          const value = set[colName] ?? sql.param(col.onUpdateFn(), col);
          const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`;
          if (i < setSize - 1) {
            return [res, sql.raw(", ")];
          }
          return [res];
        }));
      }
      buildUpdateQuery({ table: table6, set, where, returning, withList, limit, orderBy }) {
        const withSql = this.buildWithCTE(withList);
        const setSql = this.buildUpdateSet(table6, set);
        const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : void 0;
        const whereSql = where ? sql` where ${where}` : void 0;
        const orderBySql = this.buildOrderBy(orderBy);
        const limitSql = this.buildLimit(limit);
        return sql`${withSql}update ${table6} set ${setSql}${whereSql}${orderBySql}${limitSql}${returningSql}`;
      }
      /**
       * Builds selection SQL with provided fields/expressions
       *
       * Examples:
       *
       * `select <selection> from`
       *
       * `insert ... returning <selection>`
       *
       * If `isSingleTable` is true, then columns won't be prefixed with table name
       */
      buildSelection(fields, { isSingleTable = false } = {}) {
        const columnsLen = fields.length;
        const chunks = fields.flatMap(({ field }, i) => {
          const chunk = [];
          if (is(field, SQL.Aliased) && field.isSelectionField) {
            chunk.push(sql.identifier(field.fieldAlias));
          } else if (is(field, SQL.Aliased) || is(field, SQL)) {
            const query = is(field, SQL.Aliased) ? field.sql : field;
            if (isSingleTable) {
              chunk.push(
                new SQL(
                  query.queryChunks.map((c) => {
                    if (is(c, SingleStoreColumn)) {
                      return sql.identifier(this.casing.getColumnCasing(c));
                    }
                    return c;
                  })
                )
              );
            } else {
              chunk.push(query);
            }
            if (is(field, SQL.Aliased)) {
              chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);
            }
          } else if (is(field, Column2)) {
            if (isSingleTable) {
              chunk.push(sql.identifier(this.casing.getColumnCasing(field)));
            } else {
              chunk.push(field);
            }
          }
          if (i < columnsLen - 1) {
            chunk.push(sql`, `);
          }
          return chunk;
        });
        return sql.join(chunks);
      }
      buildLimit(limit) {
        return typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
      }
      buildOrderBy(orderBy) {
        return orderBy && orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : void 0;
      }
      buildSelectQuery({
        withList,
        fields,
        fieldsFlat,
        where,
        having,
        table: table6,
        joins,
        orderBy,
        groupBy,
        limit,
        offset,
        lockingClause,
        distinct,
        setOperators
      }) {
        const fieldsList = fieldsFlat ?? orderSelectedFields(fields);
        for (const f of fieldsList) {
          if (is(f.field, Column2) && getTableName(f.field.table) !== (is(table6, Subquery) ? table6._.alias : is(table6, SQL) ? void 0 : getTableName(table6)) && !((table22) => joins?.some(
            ({ alias }) => alias === (table22[Table2.Symbol.IsAlias] ? getTableName(table22) : table22[Table2.Symbol.BaseName])
          ))(f.field.table)) {
            const tableName = getTableName(f.field.table);
            throw new Error(
              `Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`
            );
          }
        }
        const isSingleTable = !joins || joins.length === 0;
        const withSql = this.buildWithCTE(withList);
        const distinctSql = distinct ? sql` distinct` : void 0;
        const selection = this.buildSelection(fieldsList, { isSingleTable });
        const tableSql = (() => {
          if (is(table6, Table2) && table6[Table2.Symbol.IsAlias]) {
            return sql`${sql`${sql.identifier(table6[Table2.Symbol.Schema] ?? "")}.`.if(table6[Table2.Symbol.Schema])}${sql.identifier(table6[Table2.Symbol.OriginalName])} ${sql.identifier(table6[Table2.Symbol.Name])}`;
          }
          return table6;
        })();
        const joinsArray = [];
        if (joins) {
          for (const [index6, joinMeta] of joins.entries()) {
            if (index6 === 0) {
              joinsArray.push(sql` `);
            }
            const table22 = joinMeta.table;
            const lateralSql = joinMeta.lateral ? sql` lateral` : void 0;
            const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0;
            if (is(table22, SingleStoreTable)) {
              const tableName = table22[SingleStoreTable.Symbol.Name];
              const tableSchema = table22[SingleStoreTable.Symbol.Schema];
              const origTableName = table22[SingleStoreTable.Symbol.OriginalName];
              const alias = tableName === origTableName ? void 0 : joinMeta.alias;
              joinsArray.push(
                sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`
              );
            } else if (is(table22, View3)) {
              const viewName = table22[ViewBaseConfig].name;
              const viewSchema = table22[ViewBaseConfig].schema;
              const origViewName = table22[ViewBaseConfig].originalName;
              const alias = viewName === origViewName ? void 0 : joinMeta.alias;
              joinsArray.push(
                sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : void 0}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`
              );
            } else {
              joinsArray.push(
                sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table22}${onSql}`
              );
            }
            if (index6 < joins.length - 1) {
              joinsArray.push(sql` `);
            }
          }
        }
        const joinsSql = sql.join(joinsArray);
        const whereSql = where ? sql` where ${where}` : void 0;
        const havingSql = having ? sql` having ${having}` : void 0;
        const orderBySql = this.buildOrderBy(orderBy);
        const groupBySql = groupBy && groupBy.length > 0 ? sql` group by ${sql.join(groupBy, sql`, `)}` : void 0;
        const limitSql = this.buildLimit(limit);
        const offsetSql = offset ? sql` offset ${offset}` : void 0;
        let lockingClausesSql;
        if (lockingClause) {
          const { config, strength } = lockingClause;
          lockingClausesSql = sql` for ${sql.raw(strength)}`;
          if (config.noWait) {
            lockingClausesSql.append(sql` nowait`);
          } else if (config.skipLocked) {
            lockingClausesSql.append(sql` skip locked`);
          }
        }
        const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClausesSql}`;
        if (setOperators.length > 0) {
          return this.buildSetOperations(finalQuery, setOperators);
        }
        return finalQuery;
      }
      buildSetOperations(leftSelect, setOperators) {
        const [setOperator, ...rest] = setOperators;
        if (!setOperator) {
          throw new Error("Cannot pass undefined values to any set operator");
        }
        if (rest.length === 0) {
          return this.buildSetOperationQuery({ leftSelect, setOperator });
        }
        return this.buildSetOperations(
          this.buildSetOperationQuery({ leftSelect, setOperator }),
          rest
        );
      }
      buildSetOperationQuery({
        leftSelect,
        setOperator: { type, isAll, rightSelect, limit, orderBy, offset }
      }) {
        const leftChunk = sql`(${leftSelect.getSQL()}) `;
        const rightChunk = sql`(${rightSelect.getSQL()})`;
        let orderBySql;
        if (orderBy && orderBy.length > 0) {
          const orderByValues = [];
          for (const orderByUnit of orderBy) {
            if (is(orderByUnit, SingleStoreColumn)) {
              orderByValues.push(sql.identifier(this.casing.getColumnCasing(orderByUnit)));
            } else if (is(orderByUnit, SQL)) {
              for (let i = 0; i < orderByUnit.queryChunks.length; i++) {
                const chunk = orderByUnit.queryChunks[i];
                if (is(chunk, SingleStoreColumn)) {
                  orderByUnit.queryChunks[i] = sql.identifier(this.casing.getColumnCasing(chunk));
                }
              }
              orderByValues.push(sql`${orderByUnit}`);
            } else {
              orderByValues.push(sql`${orderByUnit}`);
            }
          }
          orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `;
        }
        const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : void 0;
        const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`);
        const offsetSql = offset ? sql` offset ${offset}` : void 0;
        return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;
      }
      buildInsertQuery({ table: table6, values, ignore, onConflict }) {
        const valuesSqlList = [];
        const columns = table6[Table2.Symbol.Columns];
        const colEntries = Object.entries(columns).filter(
          ([_2, col]) => !col.shouldDisableInsert()
        );
        const insertOrder = colEntries.map(([, column6]) => sql.identifier(this.casing.getColumnCasing(column6)));
        const generatedIdsResponse = [];
        for (const [valueIndex, value] of values.entries()) {
          const generatedIds = {};
          const valueList = [];
          for (const [fieldName, col] of colEntries) {
            const colValue = value[fieldName];
            if (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) {
              if (col.defaultFn !== void 0) {
                const defaultFnResult = col.defaultFn();
                generatedIds[fieldName] = defaultFnResult;
                const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);
                valueList.push(defaultValue);
              } else if (!col.default && col.onUpdateFn !== void 0) {
                const onUpdateFnResult = col.onUpdateFn();
                const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);
                valueList.push(newValue);
              } else {
                valueList.push(sql`default`);
              }
            } else {
              if (col.defaultFn && is(colValue, Param)) {
                generatedIds[fieldName] = colValue.value;
              }
              valueList.push(colValue);
            }
          }
          generatedIdsResponse.push(generatedIds);
          valuesSqlList.push(valueList);
          if (valueIndex < values.length - 1) {
            valuesSqlList.push(sql`, `);
          }
        }
        const valuesSql = sql.join(valuesSqlList);
        const ignoreSql = ignore ? sql` ignore` : void 0;
        const onConflictSql = onConflict ? sql` on duplicate key ${onConflict}` : void 0;
        return {
          sql: sql`insert${ignoreSql} into ${table6} ${insertOrder} values ${valuesSql}${onConflictSql}`,
          generatedIds: generatedIdsResponse
        };
      }
      sqlToQuery(sql2, invokeSource) {
        return sql2.toQuery({
          casing: this.casing,
          escapeName: this.escapeName,
          escapeParam: this.escapeParam,
          escapeString: this.escapeString,
          invokeSource
        });
      }
      buildRelationalQuery({
        fullSchema,
        schema: schema5,
        tableNamesMap,
        table: table6,
        tableConfig,
        queryConfig: config,
        tableAlias,
        nestedQueryRelation,
        joinOn
      }) {
        let selection = [];
        let limit, offset, orderBy, where;
        const joins = [];
        if (config === true) {
          const selectionEntries = Object.entries(tableConfig.columns);
          selection = selectionEntries.map(([key, value]) => ({
            dbKey: value.name,
            tsKey: key,
            field: aliasedTableColumn(value, tableAlias),
            relationTableTsKey: void 0,
            isJson: false,
            selection: []
          }));
        } else {
          const aliasedColumns = Object.fromEntries(
            Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)])
          );
          if (config.where) {
            const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where;
            where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias);
          }
          const fieldsSelection = [];
          let selectedColumns = [];
          if (config.columns) {
            let isIncludeMode = false;
            for (const [field, value] of Object.entries(config.columns)) {
              if (value === void 0) {
                continue;
              }
              if (field in tableConfig.columns) {
                if (!isIncludeMode && value === true) {
                  isIncludeMode = true;
                }
                selectedColumns.push(field);
              }
            }
            if (selectedColumns.length > 0) {
              selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key));
            }
          } else {
            selectedColumns = Object.keys(tableConfig.columns);
          }
          for (const field of selectedColumns) {
            const column6 = tableConfig.columns[field];
            fieldsSelection.push({ tsKey: field, value: column6 });
          }
          let selectedRelations = [];
          if (config.with) {
            selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] }));
          }
          let extras;
          if (config.extras) {
            extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras;
            for (const [tsKey, value] of Object.entries(extras)) {
              fieldsSelection.push({
                tsKey,
                value: mapColumnsInAliasedSQLToAlias(value, tableAlias)
              });
            }
          }
          for (const { tsKey, value } of fieldsSelection) {
            selection.push({
              dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name,
              tsKey,
              field: is(value, Column2) ? aliasedTableColumn(value, tableAlias) : value,
              relationTableTsKey: void 0,
              isJson: false,
              selection: []
            });
          }
          let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? [];
          if (!Array.isArray(orderByOrig)) {
            orderByOrig = [orderByOrig];
          }
          orderBy = orderByOrig.map((orderByValue) => {
            if (is(orderByValue, Column2)) {
              return aliasedTableColumn(orderByValue, tableAlias);
            }
            return mapColumnsInSQLToAlias(orderByValue, tableAlias);
          });
          limit = config.limit;
          offset = config.offset;
          for (const {
            tsKey: selectedRelationTsKey,
            queryConfig: selectedRelationConfigValue,
            relation
          } of selectedRelations) {
            const normalizedRelation = normalizeRelation(schema5, tableNamesMap, relation);
            const relationTableName = getTableUniqueName(relation.referencedTable);
            const relationTableTsName = tableNamesMap[relationTableName];
            const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`;
            const joinOn2 = and(
              ...normalizedRelation.fields.map(
                (field2, i) => eq(
                  aliasedTableColumn(normalizedRelation.references[i], relationTableAlias),
                  aliasedTableColumn(field2, tableAlias)
                )
              )
            );
            const builtRelation = this.buildRelationalQuery({
              fullSchema,
              schema: schema5,
              tableNamesMap,
              table: fullSchema[relationTableTsName],
              tableConfig: schema5[relationTableTsName],
              queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue,
              tableAlias: relationTableAlias,
              joinOn: joinOn2,
              nestedQueryRelation: relation
            });
            const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier("data")}`.as(selectedRelationTsKey);
            joins.push({
              on: sql`true`,
              table: new Subquery(builtRelation.sql, {}, relationTableAlias),
              alias: relationTableAlias,
              joinType: "left",
              lateral: true
            });
            selection.push({
              dbKey: selectedRelationTsKey,
              tsKey: selectedRelationTsKey,
              field,
              relationTableTsKey: relationTableTsName,
              isJson: true,
              selection: builtRelation.selection
            });
          }
        }
        if (selection.length === 0) {
          throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` });
        }
        let result;
        where = and(joinOn, where);
        if (nestedQueryRelation) {
          let field = sql`JSON_TO_ARRAY(${sql.join(
            selection.map(
              ({ field: field2, tsKey, isJson }) => isJson ? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2
            ),
            sql`, `
          )})`;
          if (is(nestedQueryRelation, Many)) {
            field = sql`json_agg(${field})`;
          }
          const nestedSelection = [{
            dbKey: "data",
            tsKey: "data",
            field: field.as("data"),
            isJson: true,
            relationTableTsKey: tableConfig.tsName,
            selection
          }];
          const needsSubquery = limit !== void 0 || offset !== void 0 || (orderBy?.length ?? 0) > 0;
          if (needsSubquery) {
            result = this.buildSelectQuery({
              table: aliasedTable(table6, tableAlias),
              fields: {},
              fieldsFlat: [
                {
                  path: [],
                  field: sql.raw("*")
                },
                ...(orderBy?.length ?? 0) > 0 ? [{
                  path: [],
                  field: sql`row_number() over (order by ${sql.join(orderBy, sql`, `)})`
                }] : []
              ],
              where,
              limit,
              offset,
              setOperators: []
            });
            where = void 0;
            limit = void 0;
            offset = void 0;
            orderBy = void 0;
          } else {
            result = aliasedTable(table6, tableAlias);
          }
          result = this.buildSelectQuery({
            table: is(result, SingleStoreTable) ? result : new Subquery(result, {}, tableAlias),
            fields: {},
            fieldsFlat: nestedSelection.map(({ field: field2 }) => ({
              path: [],
              field: is(field2, Column2) ? aliasedTableColumn(field2, tableAlias) : field2
            })),
            joins,
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        } else {
          result = this.buildSelectQuery({
            table: aliasedTable(table6, tableAlias),
            fields: {},
            fieldsFlat: selection.map(({ field }) => ({
              path: [],
              field: is(field, Column2) ? aliasedTableColumn(field, tableAlias) : field
            })),
            joins,
            where,
            limit,
            offset,
            orderBy,
            setOperators: []
          });
        }
        return {
          tableTsKey: tableConfig.tsName,
          sql: result,
          selection
        };
      }
    };
    __publicField(SingleStoreDialect, _a425, "SingleStoreDialect");
  }
});

// ../drizzle-orm/dist/singlestore-core/query-builders/select.js
function createSetOperator4(type, isAll) {
  return (leftSelect, rightSelect, ...restSelects) => {
    const setOperators = [rightSelect, ...restSelects].map((select) => ({
      type,
      isAll,
      rightSelect: select
    }));
    for (const setOperator of setOperators) {
      if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) {
        throw new Error(
          "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
        );
      }
    }
    return leftSelect.addSetOperators(setOperators);
  };
}
var _a426, SingleStoreSelectBuilder, _a427, _b322, SingleStoreSelectQueryBuilderBase, _a428, _b323, SingleStoreSelectBase, getSingleStoreSetOperators, union5, unionAll4, intersect4, except4, minus;
var init_select5 = __esm({
  "../drizzle-orm/dist/singlestore-core/query-builders/select.js"() {
    "use strict";
    init_entity();
    init_query_builder();
    init_query_promise();
    init_selection_proxy();
    init_sql();
    init_subquery();
    init_table();
    init_utils2();
    init_utils10();
    _a426 = entityKind;
    SingleStoreSelectBuilder = class {
      constructor(config) {
        __publicField(this, "fields");
        __publicField(this, "session");
        __publicField(this, "dialect");
        __publicField(this, "withList", []);
        __publicField(this, "distinct");
        this.fields = config.fields;
        this.session = config.session;
        this.dialect = config.dialect;
        if (config.withList) {
          this.withList = config.withList;
        }
        this.distinct = config.distinct;
      }
      from(source) {
        const isPartialSelect = !!this.fields;
        let fields;
        if (this.fields) {
          fields = this.fields;
        } else if (is(source, Subquery)) {
          fields = Object.fromEntries(
            Object.keys(source._.selectedFields).map((key) => [key, source[key]])
          );
        } else if (is(source, SQL)) {
          fields = {};
        } else {
          fields = getTableColumns(source);
        }
        return new SingleStoreSelectBase(
          {
            table: source,
            fields,
            isPartialSelect,
            session: this.session,
            dialect: this.dialect,
            withList: this.withList,
            distinct: this.distinct
          }
        );
      }
    };
    __publicField(SingleStoreSelectBuilder, _a426, "SingleStoreSelectBuilder");
    SingleStoreSelectQueryBuilderBase = class extends (_b322 = TypedQueryBuilder, _a427 = entityKind, _b322) {
      constructor({ table: table6, fields, isPartialSelect, session, dialect: dialect6, withList, distinct }) {
        super();
        __publicField(this, "_");
        __publicField(this, "config");
        __publicField(this, "joinsNotNullableMap");
        __publicField(this, "tableName");
        __publicField(this, "isPartialSelect");
        /** @internal */
        __publicField(this, "session");
        __publicField(this, "dialect");
        __publicField(this, "cacheConfig");
        __publicField(this, "usedTables", /* @__PURE__ */ new Set());
        /**
         * Executes a `left join` operation by adding another table to the current query.
         *
         * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#left-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select()
         *   .from(users)
         *   .leftJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .leftJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "leftJoin", this.createJoin("left", false));
        /**
         * Executes a `left join lateral` operation by adding subquery to the current query.
         *
         * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
         *
         * Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#left-join-lateral}
         *
         * @param table the subquery to join.
         * @param on the `on` clause.
         */
        __publicField(this, "leftJoinLateral", this.createJoin("left", true));
        /**
         * Executes a `right join` operation by adding another table to the current query.
         *
         * Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#right-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select()
         *   .from(users)
         *   .rightJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .rightJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "rightJoin", this.createJoin("right", false));
        /**
         * Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.
         *
         * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
         *   .from(users)
         *   .innerJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .innerJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "innerJoin", this.createJoin("inner", false));
        /**
         * Executes an `inner join lateral` operation, creating a new table by combining rows from two queries that have matching values.
         *
         * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
         *
         * Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#inner-join-lateral}
         *
         * @param table the subquery to join.
         * @param on the `on` clause.
         */
        __publicField(this, "innerJoinLateral", this.createJoin("inner", true));
        /**
         * Executes a `full join` operation by combining rows from two tables into a new table.
         *
         * Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#full-join}
         *
         * @param table the table to join.
         * @param on the `on` clause.
         *
         * @example
         *
         * ```ts
         * // Select all users and their pets
         * const usersWithPets: { user: User | null; pets: Pet | null; }[] = await db.select()
         *   .from(users)
         *   .fullJoin(pets, eq(users.id, pets.ownerId))
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number | null; petId: number | null; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .fullJoin(pets, eq(users.id, pets.ownerId))
         * ```
         */
        __publicField(this, "fullJoin", this.createJoin("full", false));
        /**
         * Executes a `cross join` operation by combining rows from two tables into a new table.
         *
         * Calling this method retrieves all rows from both main and joined tables, merging all rows from each table.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}
         *
         * @param table the table to join.
         *
         * @example
         *
         * ```ts
         * // Select all users, each user with every pet
         * const usersWithPets: { user: User; pets: Pet; }[] = await db.select()
         *   .from(users)
         *   .crossJoin(pets)
         *
         * // Select userId and petId
         * const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({
         *   userId: users.id,
         *   petId: pets.id,
         * })
         *   .from(users)
         *   .crossJoin(pets)
         * ```
         */
        __publicField(this, "crossJoin", this.createJoin("cross", false));
        /**
         * Executes a `cross join lateral` operation by combining rows from two queries into a new table.
         *
         * A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.
         *
         * Calling this method retrieves all rows from both main and joined queries, merging all rows from each query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/joins#cross-join-lateral}
         *
         * @param table the query to join.
         */
        __publicField(this, "crossJoinLateral", this.createJoin("cross", true));
        /**
         * Adds `union` set operator to the query.
         *
         * Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#union}
         *
         * @example
         *
         * ```ts
         * // Select all unique names from customers and users tables
         * await db.select({ name: users.name })
         *   .from(users)
         *   .union(
         *     db.select({ name: customers.name }).from(customers)
         *   );
         * // or
         * import { union } from 'drizzle-orm/singlestore-core'
         *
         * await union(
         *   db.select({ name: users.name }).from(users),
         *   db.select({ name: customers.name }).from(customers)
         * );
         * ```
         */
        __publicField(this, "union", this.createSetOperator("union", false));
        /**
         * Adds `union all` set operator to the query.
         *
         * Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}
         *
         * @example
         *
         * ```ts
         * // Select all transaction ids from both online and in-store sales
         * await db.select({ transaction: onlineSales.transactionId })
         *   .from(onlineSales)
         *   .unionAll(
         *     db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
         *   );
         * // or
         * import { unionAll } from 'drizzle-orm/singlestore-core'
         *
         * await unionAll(
         *   db.select({ transaction: onlineSales.transactionId }).from(onlineSales),
         *   db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)
         * );
         * ```
         */
        __publicField(this, "unionAll", this.createSetOperator("union", true));
        /**
         * Adds `intersect` set operator to the query.
         *
         * Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}
         *
         * @example
         *
         * ```ts
         * // Select course names that are offered in both departments A and B
         * await db.select({ courseName: depA.courseName })
         *   .from(depA)
         *   .intersect(
         *     db.select({ courseName: depB.courseName }).from(depB)
         *   );
         * // or
         * import { intersect } from 'drizzle-orm/singlestore-core'
         *
         * await intersect(
         *   db.select({ courseName: depA.courseName }).from(depA),
         *   db.select({ courseName: depB.courseName }).from(depB)
         * );
         * ```
         */
        __publicField(this, "intersect", this.createSetOperator("intersect", false));
        /**
         * Adds `except` set operator to the query.
         *
         * Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/set-operations#except}
         *
         * @example
         *
         * ```ts
         * // Select all courses offered in department A but not in department B
         * await db.select({ courseName: depA.courseName })
         *   .from(depA)
         *   .except(
         *     db.select({ courseName: depB.courseName }).from(depB)
         *   );
         * // or
         * import { except } from 'drizzle-orm/singlestore-core'
         *
         * await except(
         *   db.select({ courseName: depA.courseName }).from(depA),
         *   db.select({ courseName: depB.courseName }).from(depB)
         * );
         * ```
         */
        __publicField(this, "except", this.createSetOperator("except", false));
        /**
         * Adds `minus` set operator to the query.
         *
         * This is an alias of `except` supported by SingleStore.
         *
         * @example
         *
         * ```ts
         * // Select all courses offered in department A but not in department B
         * await db.select({ courseName: depA.courseName })
         *   .from(depA)
         *   .minus(
         *     db.select({ courseName: depB.courseName }).from(depB)
         *   );
         * // or
         * import { minus } from 'drizzle-orm/singlestore-core'
         *
         * await minus(
         *   db.select({ courseName: depA.courseName }).from(depA),
         *   db.select({ courseName: depB.courseName }).from(depB)
         * );
         * ```
         */
        __publicField(this, "minus", this.createSetOperator("except", false));
        this.config = {
          withList,
          table: table6,
          fields: { ...fields },
          distinct,
          setOperators: []
        };
        this.isPartialSelect = isPartialSelect;
        this.session = session;
        this.dialect = dialect6;
        this._ = {
          selectedFields: fields,
          config: this.config
        };
        this.tableName = getTableLikeName(table6);
        this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {};
        for (const item of extractUsedTable4(table6)) this.usedTables.add(item);
      }
      /** @internal */
      getUsedTables() {
        return [...this.usedTables];
      }
      createJoin(joinType, lateral) {
        return (table6, on) => {
          const baseTableName = this.tableName;
          const tableName = getTableLikeName(table6);
          for (const item of extractUsedTable4(table6)) this.usedTables.add(item);
          if (typeof tableName === "string" && this.config.joins?.some((join) => join.alias === tableName)) {
            throw new Error(`Alias "${tableName}" is already used in this query`);
          }
          if (!this.isPartialSelect) {
            if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") {
              this.config.fields = {
                [baseTableName]: this.config.fields
              };
            }
            if (typeof tableName === "string" && !is(table6, SQL)) {
              const selection = is(table6, Subquery) ? table6._.selectedFields : table6[Table2.Symbol.Columns];
              this.config.fields[tableName] = selection;
            }
          }
          if (typeof on === "function") {
            on = on(
              new Proxy(
                this.config.fields,
                new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
              )
            );
          }
          if (!this.config.joins) {
            this.config.joins = [];
          }
          this.config.joins.push({ on, table: table6, joinType, alias: tableName, lateral });
          if (typeof tableName === "string") {
            switch (joinType) {
              case "left": {
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
              case "right": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "cross":
              case "inner": {
                this.joinsNotNullableMap[tableName] = true;
                break;
              }
              case "full": {
                this.joinsNotNullableMap = Object.fromEntries(
                  Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])
                );
                this.joinsNotNullableMap[tableName] = false;
                break;
              }
            }
          }
          return this;
        };
      }
      createSetOperator(type, isAll) {
        return (rightSelection) => {
          const rightSelect = typeof rightSelection === "function" ? rightSelection(getSingleStoreSetOperators()) : rightSelection;
          if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) {
            throw new Error(
              "Set operator error (union / intersect / except): selected fields are not the same or are in a different order"
            );
          }
          this.config.setOperators.push({ type, isAll, rightSelect });
          return this;
        };
      }
      /** @internal */
      addSetOperators(setOperators) {
        this.config.setOperators.push(...setOperators);
        return this;
      }
      /**
       * Adds a `where` clause to the query.
       *
       * Calling this method will select only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#filtering}
       *
       * @param where the `where` clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be selected.
       *
       * ```ts
       * // Select all cars with green color
       * await db.select().from(cars).where(eq(cars.color, 'green'));
       * // or
       * await db.select().from(cars).where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Select all BMW cars with a green color
       * await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Select all cars with the green or blue color
       * await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        if (typeof where === "function") {
          where = where(
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
            )
          );
        }
        this.config.where = where;
        return this;
      }
      /**
       * Adds a `having` clause to the query.
       *
       * Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#aggregations}
       *
       * @param having the `having` clause.
       *
       * @example
       *
       * ```ts
       * // Select all brands with more than one car
       * await db.select({
       * 	brand: cars.brand,
       * 	count: sql<number>`cast(count(${cars.id}) as int)`,
       * })
       *   .from(cars)
       *   .groupBy(cars.brand)
       *   .having(({ count }) => gt(count, 1));
       * ```
       */
      having(having) {
        if (typeof having === "function") {
          having = having(
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })
            )
          );
        }
        this.config.having = having;
        return this;
      }
      groupBy(...columns) {
        if (typeof columns[0] === "function") {
          const groupBy = columns[0](
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];
        } else {
          this.config.groupBy = columns;
        }
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.fields,
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          if (this.config.setOperators.length > 0) {
            this.config.setOperators.at(-1).orderBy = orderByArray;
          } else {
            this.config.orderBy = orderByArray;
          }
        } else {
          const orderByArray = columns;
          if (this.config.setOperators.length > 0) {
            this.config.setOperators.at(-1).orderBy = orderByArray;
          } else {
            this.config.orderBy = orderByArray;
          }
        }
        return this;
      }
      /**
       * Adds a `limit` clause to the query.
       *
       * Calling this method will set the maximum number of rows that will be returned by this query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
       *
       * @param limit the `limit` clause.
       *
       * @example
       *
       * ```ts
       * // Get the first 10 people from this query.
       * await db.select().from(people).limit(10);
       * ```
       */
      limit(limit) {
        if (this.config.setOperators.length > 0) {
          this.config.setOperators.at(-1).limit = limit;
        } else {
          this.config.limit = limit;
        }
        return this;
      }
      /**
       * Adds an `offset` clause to the query.
       *
       * Calling this method will skip a number of rows when returning results from this query.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}
       *
       * @param offset the `offset` clause.
       *
       * @example
       *
       * ```ts
       * // Get the 10th-20th people from this query.
       * await db.select().from(people).offset(10).limit(10);
       * ```
       */
      offset(offset) {
        if (this.config.setOperators.length > 0) {
          this.config.setOperators.at(-1).offset = offset;
        } else {
          this.config.offset = offset;
        }
        return this;
      }
      /**
       * Adds a `for` clause to the query.
       *
       * Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried.
       *
       * @param strength the lock strength.
       * @param config the lock configuration.
       */
      for(strength, config = {}) {
        this.config.lockingClause = { strength, config };
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildSelectQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      as(alias) {
        const usedTables = [];
        usedTables.push(...extractUsedTable4(this.config.table));
        if (this.config.joins) {
          for (const it of this.config.joins) usedTables.push(...extractUsedTable4(it.table));
        }
        return new Proxy(
          new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]),
          new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
        );
      }
      /** @internal */
      getSelectedFields() {
        return new Proxy(
          this.config.fields,
          new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
        );
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(SingleStoreSelectQueryBuilderBase, _a427, "SingleStoreSelectQueryBuilder");
    SingleStoreSelectBase = class extends (_b323 = SingleStoreSelectQueryBuilderBase, _a428 = entityKind, _b323) {
      constructor() {
        super(...arguments);
        __publicField(this, "execute", (placeholderValues) => {
          return this.prepare().execute(placeholderValues);
        });
        __publicField(this, "createIterator", () => {
          const self2 = this;
          return async function* (placeholderValues) {
            yield* self2.prepare().iterator(placeholderValues);
          };
        });
        __publicField(this, "iterator", this.createIterator());
      }
      prepare() {
        if (!this.session) {
          throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");
        }
        const fieldsList = orderSelectedFields(this.config.fields);
        const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), fieldsList, void 0, void 0, void 0, {
          type: "select",
          tables: [...this.usedTables]
        }, this.cacheConfig);
        query.joinsNotNullableMap = this.joinsNotNullableMap;
        return query;
      }
      $withCache(config) {
        this.cacheConfig = config === void 0 ? { config: {}, enable: true, autoInvalidate: true } : config === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config };
        return this;
      }
    };
    __publicField(SingleStoreSelectBase, _a428, "SingleStoreSelect");
    applyMixins(SingleStoreSelectBase, [QueryPromise]);
    getSingleStoreSetOperators = () => ({
      union: union5,
      unionAll: unionAll4,
      intersect: intersect4,
      except: except4,
      minus
    });
    union5 = createSetOperator4("union", false);
    unionAll4 = createSetOperator4("union", true);
    intersect4 = createSetOperator4("intersect", false);
    except4 = createSetOperator4("except", false);
    minus = createSetOperator4("except", true);
  }
});

// ../drizzle-orm/dist/singlestore-core/query-builders/query-builder.js
var _a429, QueryBuilder4;
var init_query_builder5 = __esm({
  "../drizzle-orm/dist/singlestore-core/query-builders/query-builder.js"() {
    "use strict";
    init_entity();
    init_selection_proxy();
    init_dialect4();
    init_subquery();
    init_select5();
    _a429 = entityKind;
    QueryBuilder4 = class {
      constructor(dialect6) {
        __publicField(this, "dialect");
        __publicField(this, "dialectConfig");
        __publicField(this, "$with", (alias, selection) => {
          const queryBuilder = this;
          const as = (qb) => {
            if (typeof qb === "function") {
              qb = qb(queryBuilder);
            }
            return new Proxy(
              new WithSubquery(
                qb.getSQL(),
                selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
                alias,
                true
              ),
              new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
            );
          };
          return { as };
        });
        this.dialect = is(dialect6, SingleStoreDialect) ? dialect6 : void 0;
        this.dialectConfig = is(dialect6, SingleStoreDialect) ? void 0 : dialect6;
      }
      with(...queries) {
        const self2 = this;
        function select(fields) {
          return new SingleStoreSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self2.getDialect(),
            withList: queries
          });
        }
        function selectDistinct(fields) {
          return new SingleStoreSelectBuilder({
            fields: fields ?? void 0,
            session: void 0,
            dialect: self2.getDialect(),
            withList: queries,
            distinct: true
          });
        }
        return { select, selectDistinct };
      }
      select(fields) {
        return new SingleStoreSelectBuilder({
          fields: fields ?? void 0,
          session: void 0,
          dialect: this.getDialect()
        });
      }
      selectDistinct(fields) {
        return new SingleStoreSelectBuilder({
          fields: fields ?? void 0,
          session: void 0,
          dialect: this.getDialect(),
          distinct: true
        });
      }
      // Lazy load dialect to avoid circular dependency
      getDialect() {
        if (!this.dialect) {
          this.dialect = new SingleStoreDialect(this.dialectConfig);
        }
        return this.dialect;
      }
    };
    __publicField(QueryBuilder4, _a429, "SingleStoreQueryBuilder");
  }
});

// ../drizzle-orm/dist/singlestore-core/query-builders/select.types.js
var init_select_types4 = __esm({
  "../drizzle-orm/dist/singlestore-core/query-builders/select.types.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/singlestore-core/query-builders/update.js
var _a430, SingleStoreUpdateBuilder, _a431, _b324, SingleStoreUpdateBase;
var init_update4 = __esm({
  "../drizzle-orm/dist/singlestore-core/query-builders/update.js"() {
    "use strict";
    init_entity();
    init_query_promise();
    init_selection_proxy();
    init_table();
    init_utils2();
    init_utils10();
    _a430 = entityKind;
    SingleStoreUpdateBuilder = class {
      constructor(table6, session, dialect6, withList) {
        this.table = table6;
        this.session = session;
        this.dialect = dialect6;
        this.withList = withList;
      }
      set(values) {
        return new SingleStoreUpdateBase(
          this.table,
          mapUpdateSet(this.table, values),
          this.session,
          this.dialect,
          this.withList
        );
      }
    };
    __publicField(SingleStoreUpdateBuilder, _a430, "SingleStoreUpdateBuilder");
    SingleStoreUpdateBase = class extends (_b324 = QueryPromise, _a431 = entityKind, _b324) {
      constructor(table6, set, session, dialect6, withList) {
        super();
        __publicField(this, "config");
        __publicField(this, "execute", (placeholderValues) => {
          return this.prepare().execute(placeholderValues);
        });
        __publicField(this, "createIterator", () => {
          const self2 = this;
          return async function* (placeholderValues) {
            yield* self2.prepare().iterator(placeholderValues);
          };
        });
        __publicField(this, "iterator", this.createIterator());
        this.session = session;
        this.dialect = dialect6;
        this.config = { set, table: table6, withList };
      }
      /**
       * Adds a 'where' clause to the query.
       *
       * Calling this method will update only those rows that fulfill a specified condition.
       *
       * See docs: {@link https://orm.drizzle.team/docs/update}
       *
       * @param where the 'where' clause.
       *
       * @example
       * You can use conditional operators and `sql function` to filter the rows to be updated.
       *
       * ```ts
       * // Update all cars with green color
       * db.update(cars).set({ color: 'red' })
       *   .where(eq(cars.color, 'green'));
       * // or
       * db.update(cars).set({ color: 'red' })
       *   .where(sql`${cars.color} = 'green'`)
       * ```
       *
       * You can logically combine conditional operators with `and()` and `or()` operators:
       *
       * ```ts
       * // Update all BMW cars with a green color
       * db.update(cars).set({ color: 'red' })
       *   .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));
       *
       * // Update all cars with the green or blue color
       * db.update(cars).set({ color: 'red' })
       *   .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));
       * ```
       */
      where(where) {
        this.config.where = where;
        return this;
      }
      orderBy(...columns) {
        if (typeof columns[0] === "function") {
          const orderBy = columns[0](
            new Proxy(
              this.config.table[Table2.Symbol.Columns],
              new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" })
            )
          );
          const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];
          this.config.orderBy = orderByArray;
        } else {
          const orderByArray = columns;
          this.config.orderBy = orderByArray;
        }
        return this;
      }
      limit(limit) {
        this.config.limit = limit;
        return this;
      }
      /** @internal */
      getSQL() {
        return this.dialect.buildUpdateQuery(this.config);
      }
      toSQL() {
        const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL());
        return rest;
      }
      prepare() {
        return this.session.prepareQuery(
          this.dialect.sqlToQuery(this.getSQL()),
          this.config.returning,
          void 0,
          void 0,
          void 0,
          {
            type: "delete",
            tables: extractUsedTable4(this.config.table)
          }
        );
      }
      $dynamic() {
        return this;
      }
    };
    __publicField(SingleStoreUpdateBase, _a431, "SingleStoreUpdate");
  }
});

// ../drizzle-orm/dist/singlestore-core/query-builders/index.js
var init_query_builders4 = __esm({
  "../drizzle-orm/dist/singlestore-core/query-builders/index.js"() {
    "use strict";
    init_delete4();
    init_insert4();
    init_query_builder5();
    init_select5();
    init_select_types4();
    init_update4();
  }
});

// ../drizzle-orm/dist/singlestore-core/db.js
var _a432, SingleStoreDatabase;
var init_db4 = __esm({
  "../drizzle-orm/dist/singlestore-core/db.js"() {
    "use strict";
    init_entity();
    init_selection_proxy();
    init_sql();
    init_subquery();
    init_count4();
    init_query_builders4();
    _a432 = entityKind;
    SingleStoreDatabase = class {
      constructor(dialect6, session, schema5) {
        // We are waiting for SingleStore support for `json_array` function
        /**@inrernal */
        __publicField(this, "query");
        /**
         * Creates a subquery that defines a temporary named result set as a CTE.
         *
         * It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.
         *
         * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
         *
         * @param alias The alias for the subquery.
         *
         * Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.
         *
         * @example
         *
         * ```ts
         * // Create a subquery with alias 'sq' and use it in the select query
         * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
         *
         * const result = await db.with(sq).select().from(sq);
         * ```
         *
         * To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:
         *
         * ```ts
         * // Select an arbitrary SQL value as a field in a CTE and reference it in the main query
         * const sq = db.$with('sq').as(db.select({
         *   name: sql<string>`upper(${users.name})`.as('name'),
         * })
         * .from(users));
         *
         * const result = await db.with(sq).select({ name: sq.name }).from(sq);
         * ```
         */
        __publicField(this, "$with", (alias, selection) => {
          const self2 = this;
          const as = (qb) => {
            if (typeof qb === "function") {
              qb = qb(new QueryBuilder4(self2.dialect));
            }
            return new Proxy(
              new WithSubquery(
                qb.getSQL(),
                selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}),
                alias,
                true
              ),
              new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })
            );
          };
          return { as };
        });
        __publicField(this, "$cache");
        this.dialect = dialect6;
        this.session = session;
        this._ = schema5 ? {
          schema: schema5.schema,
          fullSchema: schema5.fullSchema,
          tableNamesMap: schema5.tableNamesMap
        } : {
          schema: void 0,
          fullSchema: {},
          tableNamesMap: {}
        };
        this.query = {};
        this.$cache = { invalidate: async (_params) => {
        } };
      }
      $count(source, filters) {
        return new SingleStoreCountBuilder({ source, filters, session: this.session });
      }
      /**
       * Incorporates a previously defined CTE (using `$with`) into the main query.
       *
       * This method allows the main query to reference a temporary named result set.
       *
       * See docs: {@link https://orm.drizzle.team/docs/select#with-clause}
       *
       * @param queries The CTEs to incorporate into the main query.
       *
       * @example
       *
       * ```ts
       * // Define a subquery 'sq' as a CTE using $with
       * const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));
       *
       * // Incorporate the CTE 'sq' into the main query and select from it
       * const result = await db.with(sq).select().from(sq);
       * ```
       */
      with(...queries) {
        const self2 = this;
        function select(fields) {
          return new SingleStoreSelectBuilder({
            fields: fields ?? void 0,
            session: self2.session,
            dialect: self2.dialect,
            withList: queries
          });
        }
        function selectDistinct(fields) {
          return new SingleStoreSelectBuilder({
            fields: fields ?? void 0,
            session: self2.session,
            dialect: self2.dialect,
            withList: queries,
            distinct: true
          });
        }
        function update(table6) {
          return new SingleStoreUpdateBuilder(table6, self2.session, self2.dialect, queries);
        }
        function delete_(table6) {
          return new SingleStoreDeleteBase(table6, self2.session, self2.dialect, queries);
        }
        return { select, selectDistinct, update, delete: delete_ };
      }
      select(fields) {
        return new SingleStoreSelectBuilder({ fields: fields ?? void 0, session: this.session, dialect: this.dialect });
      }
      selectDistinct(fields) {
        return new SingleStoreSelectBuilder({
          fields: fields ?? void 0,
          session: this.session,
          dialect: this.dialect,
          distinct: true
        });
      }
      /**
       * Creates an update query.
       *
       * Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.
       *
       * Use `.set()` method to specify which values to update.
       *
       * See docs: {@link https://orm.drizzle.team/docs/update}
       *
       * @param table The table to update.
       *
       * @example
       *
       * ```ts
       * // Update all rows in the 'cars' table
       * await db.update(cars).set({ color: 'red' });
       *
       * // Update rows with filters and conditions
       * await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));
       * ```
       */
      update(table6) {
        return new SingleStoreUpdateBuilder(table6, this.session, this.dialect);
      }
      /**
       * Creates an insert query.
       *
       * Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.
       *
       * See docs: {@link https://orm.drizzle.team/docs/insert}
       *
       * @param table The table to insert into.
       *
       * @example
       *
       * ```ts
       * // Insert one row
       * await db.insert(cars).values({ brand: 'BMW' });
       *
       * // Insert multiple rows
       * await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);
       * ```
       */
      insert(table6) {
        return new SingleStoreInsertBuilder(table6, this.session, this.dialect);
      }
      /**
       * Creates a delete query.
       *
       * Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.
       *
       * See docs: {@link https://orm.drizzle.team/docs/delete}
       *
       * @param table The table to delete from.
       *
       * @example
       *
       * ```ts
       * // Delete all rows in the 'cars' table
       * await db.delete(cars);
       *
       * // Delete rows with filters and conditions
       * await db.delete(cars).where(eq(cars.color, 'green'));
       * ```
       */
      delete(table6) {
        return new SingleStoreDeleteBase(table6, this.session, this.dialect);
      }
      execute(query) {
        return this.session.execute(typeof query === "string" ? sql.raw(query) : query.getSQL());
      }
      transaction(transaction, config) {
        return this.session.transaction(transaction, config);
      }
    };
    __publicField(SingleStoreDatabase, _a432, "SingleStoreDatabase");
  }
});

// ../drizzle-orm/dist/singlestore-core/schema.js
var _a433, SingleStoreSchema5;
var init_schema3 = __esm({
  "../drizzle-orm/dist/singlestore-core/schema.js"() {
    "use strict";
    init_entity();
    init_table5();
    _a433 = entityKind;
    SingleStoreSchema5 = class {
      constructor(schemaName) {
        __publicField(this, "table", (name2, columns, extraConfig) => {
          return singlestoreTableWithSchema(name2, columns, extraConfig, this.schemaName);
        });
        this.schemaName = schemaName;
      }
      /*
      view = ((name, columns) => {
      	return singlestoreViewWithSchema(name, columns, this.schemaName);
      }) as typeof singlestoreView; */
    };
    __publicField(SingleStoreSchema5, _a433, "SingleStoreSchema");
  }
});

// ../drizzle-orm/dist/singlestore-core/session.js
var _a434, SingleStorePreparedQuery, _a435, SingleStoreSession, _a436, _b325, SingleStoreTransaction;
var init_session4 = __esm({
  "../drizzle-orm/dist/singlestore-core/session.js"() {
    "use strict";
    init_cache();
    init_entity();
    init_errors2();
    init_errors3();
    init_sql();
    init_db4();
    _a434 = entityKind;
    SingleStorePreparedQuery = class {
      constructor(cache, queryMetadata, cacheConfig) {
        /** @internal */
        __publicField(this, "joinsNotNullableMap");
        this.cache = cache;
        this.queryMetadata = queryMetadata;
        this.cacheConfig = cacheConfig;
        if (cache && cache.strategy() === "all" && cacheConfig === void 0) {
          this.cacheConfig = { enable: true, autoInvalidate: true };
        }
        if (!this.cacheConfig?.enable) {
          this.cacheConfig = void 0;
        }
      }
      /** @internal */
      async queryWithCache(queryString, params, query) {
        if (this.cache === void 0 || is(this.cache, NoopCache) || this.queryMetadata === void 0) {
          try {
            return await query();
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if (this.cacheConfig && !this.cacheConfig.enable) {
          try {
            return await query();
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) {
          try {
            const [res] = await Promise.all([
              query(),
              this.cache.onMutate({ tables: this.queryMetadata.tables })
            ]);
            return res;
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if (!this.cacheConfig) {
          try {
            return await query();
          } catch (e) {
            throw new DrizzleQueryError(queryString, params, e);
          }
        }
        if (this.queryMetadata.type === "select") {
          const fromCache = await this.cache.get(
            this.cacheConfig.tag ?? await hashQuery(queryString, params),
            this.queryMetadata.tables,
            this.cacheConfig.tag !== void 0,
            this.cacheConfig.autoInvalidate
          );
          if (fromCache === void 0) {
            let result;
            try {
              result = await query();
            } catch (e) {
              throw new DrizzleQueryError(queryString, params, e);
            }
            await this.cache.put(
              this.cacheConfig.tag ?? await hashQuery(queryString, params),
              result,
              // make sure we send tables that were used in a query only if user wants to invalidate it on each write
              this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [],
              this.cacheConfig.tag !== void 0,
              this.cacheConfig.config
            );
            return result;
          }
          return fromCache;
        }
        try {
          return await query();
        } catch (e) {
          throw new DrizzleQueryError(queryString, params, e);
        }
      }
    };
    __publicField(SingleStorePreparedQuery, _a434, "SingleStorePreparedQuery");
    _a435 = entityKind;
    SingleStoreSession = class {
      constructor(dialect6) {
        this.dialect = dialect6;
      }
      execute(query) {
        return this.prepareQuery(
          this.dialect.sqlToQuery(query),
          void 0
        ).execute();
      }
      async count(sql2) {
        const res = await this.execute(sql2);
        return Number(
          res[0][0]["count"]
        );
      }
      getSetTransactionSQL(config) {
        const parts = [];
        if (config.isolationLevel) {
          parts.push(`isolation level ${config.isolationLevel}`);
        }
        return parts.length ? sql`set transaction ${sql.raw(parts.join(" "))}` : void 0;
      }
      getStartTransactionSQL(config) {
        const parts = [];
        if (config.withConsistentSnapshot) {
          parts.push("with consistent snapshot");
        }
        if (config.accessMode) {
          parts.push(config.accessMode);
        }
        return parts.length ? sql`start transaction ${sql.raw(parts.join(" "))}` : void 0;
      }
    };
    __publicField(SingleStoreSession, _a435, "SingleStoreSession");
    SingleStoreTransaction = class extends (_b325 = SingleStoreDatabase, _a436 = entityKind, _b325) {
      constructor(dialect6, session, schema5, nestedIndex) {
        super(dialect6, session, schema5);
        this.schema = schema5;
        this.nestedIndex = nestedIndex;
      }
      rollback() {
        throw new TransactionRollbackError();
      }
    };
    __publicField(SingleStoreTransaction, _a436, "SingleStoreTransaction");
  }
});

// ../drizzle-orm/dist/singlestore-core/subquery.js
var init_subquery5 = __esm({
  "../drizzle-orm/dist/singlestore-core/subquery.js"() {
    "use strict";
  }
});

// ../drizzle-orm/dist/singlestore-core/index.js
var init_singlestore_core = __esm({
  "../drizzle-orm/dist/singlestore-core/index.js"() {
    "use strict";
    init_alias5();
    init_columns4();
    init_db4();
    init_dialect4();
    init_indexes4();
    init_primary_keys4();
    init_query_builders4();
    init_schema3();
    init_session4();
    init_subquery5();
    init_table5();
    init_unique_constraint4();
    init_utils10();
  }
});

// src/serializer/singlestoreSerializer.ts
function clearDefaults2(defaultValue, collate) {
  if (typeof collate === "undefined" || collate === null) {
    collate = `utf8mb4`;
  }
  let resultDefault = defaultValue;
  collate = `_${collate}`;
  if (defaultValue.startsWith(collate)) {
    resultDefault = resultDefault.substring(collate.length, defaultValue.length).replace(/\\/g, "");
    if (resultDefault.startsWith("'") && resultDefault.endsWith("'")) {
      return `('${resultDefault.substring(1, resultDefault.length - 1)}')`;
    } else {
      return `'${resultDefault}'`;
    }
  } else {
    return `(${resultDefault})`;
  }
}
var dialect5, generateSingleStoreSnapshot, fromDatabase4;
var init_singlestoreSerializer = __esm({
  "src/serializer/singlestoreSerializer.ts"() {
    "use strict";
    init_source();
    init_dist();
    init_singlestore_core();
    init_outputs();
    init_utils6();
    dialect5 = new SingleStoreDialect();
    generateSingleStoreSnapshot = (tables, casing2) => {
      const dialect6 = new SingleStoreDialect({ casing: casing2 });
      const result = {};
      const internal = { tables: {}, indexes: {} };
      for (const table6 of tables) {
        const {
          name: tableName,
          columns,
          indexes,
          schema: schema5,
          primaryKeys,
          uniqueConstraints
        } = getTableConfig4(table6);
        const columnsObject = {};
        const indexesObject = {};
        const primaryKeysObject = {};
        const uniqueConstraintObject = {};
        columns.forEach((column6) => {
          const notNull = column6.notNull;
          const sqlTypeLowered = column6.getSQLType().toLowerCase();
          const autoIncrement = typeof column6.autoIncrement === "undefined" ? false : column6.autoIncrement;
          const generated = column6.generated;
          const columnToSet = {
            name: column6.name,
            type: column6.getSQLType(),
            primaryKey: false,
            // If field is autoincrement it's notNull by default
            // notNull: autoIncrement ? true : notNull,
            notNull,
            autoincrement: autoIncrement,
            onUpdate: column6.hasOnUpdateNow,
            generated: generated ? {
              as: is(generated.as, SQL) ? dialect6.sqlToQuery(generated.as).sql : typeof generated.as === "function" ? dialect6.sqlToQuery(generated.as()).sql : generated.as,
              type: generated.mode ?? "stored"
            } : void 0
          };
          if (column6.primary) {
            primaryKeysObject[`${tableName}_${column6.name}`] = {
              name: `${tableName}_${column6.name}`,
              columns: [column6.name]
            };
          }
          if (column6.isUnique) {
            const existingUnique = uniqueConstraintObject[column6.uniqueName];
            if (typeof existingUnique !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(`We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
          The unique constraint ${source_default.underline.blue(
                  column6.uniqueName
                )} on the ${source_default.underline.blue(
                  column6.name
                )} column is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`)}`
              );
              process.exit(1);
            }
            uniqueConstraintObject[column6.uniqueName] = {
              name: column6.uniqueName,
              columns: [columnToSet.name]
            };
          }
          if (column6.default !== void 0) {
            if (is(column6.default, SQL)) {
              columnToSet.default = sqlToStr(column6.default, casing2);
            } else {
              if (typeof column6.default === "string") {
                columnToSet.default = `'${column6.default}'`;
              } else {
                if (sqlTypeLowered === "json" || Array.isArray(column6.default)) {
                  columnToSet.default = `'${JSON.stringify(column6.default)}'`;
                } else if (column6.default instanceof Date) {
                  if (sqlTypeLowered === "date") {
                    columnToSet.default = `'${column6.default.toISOString().split("T")[0]}'`;
                  } else if (sqlTypeLowered.startsWith("datetime") || sqlTypeLowered.startsWith("timestamp")) {
                    columnToSet.default = `'${column6.default.toISOString().replace("T", " ").slice(0, 23)}'`;
                  }
                } else {
                  columnToSet.default = column6.default;
                }
              }
            }
          }
          columnsObject[column6.name] = columnToSet;
        });
        primaryKeys.map((pk) => {
          const columnNames = pk.columns.map((c) => c.name);
          primaryKeysObject[pk.getName()] = {
            name: pk.getName(),
            columns: columnNames
          };
          for (const column6 of pk.columns) {
            columnsObject[column6.name].notNull = true;
          }
        });
        uniqueConstraints?.map((unq) => {
          const columnNames = unq.columns.map((c) => c.name);
          const name2 = unq.name ?? uniqueKeyName4(table6, columnNames);
          const existingUnique = uniqueConstraintObject[name2];
          if (typeof existingUnique !== "undefined") {
            console.log(
              `
${withStyle.errorWarning(
                `We've found duplicated unique constraint names in ${source_default.underline.blue(
                  tableName
                )} table. 
The unique constraint ${source_default.underline.blue(
                  name2
                )} on the ${source_default.underline.blue(
                  columnNames.join(",")
                )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                  existingUnique.columns.join(",")
                )} columns
`
              )}`
            );
            process.exit(1);
          }
          uniqueConstraintObject[name2] = {
            name: unq.name,
            columns: columnNames
          };
        });
        indexes.forEach((value) => {
          const columns2 = value.config.columns;
          const name2 = value.config.name;
          let indexColumns = columns2.map((it) => {
            if (is(it, SQL)) {
              const sql2 = dialect6.sqlToQuery(it, "indexes").sql;
              if (typeof internal.indexes[name2] === "undefined") {
                internal.indexes[name2] = {
                  columns: {
                    [sql2]: {
                      isExpression: true
                    }
                  }
                };
              } else {
                if (typeof internal.indexes[name2]?.columns[sql2] === "undefined") {
                  internal.indexes[name2].columns[sql2] = {
                    isExpression: true
                  };
                } else {
                  internal.indexes[name2].columns[sql2].isExpression = true;
                }
              }
              return sql2;
            } else {
              return `${it.name}`;
            }
          });
          if (value.config.unique) {
            if (typeof uniqueConstraintObject[name2] !== "undefined") {
              console.log(
                `
${withStyle.errorWarning(
                  `We've found duplicated unique constraint names in ${source_default.underline.blue(
                    tableName
                  )} table. 
The unique index ${source_default.underline.blue(
                    name2
                  )} on the ${source_default.underline.blue(
                    indexColumns.join(",")
                  )} columns is confilcting with a unique constraint name already defined for ${source_default.underline.blue(
                    uniqueConstraintObject[name2].columns.join(",")
                  )} columns
`
                )}`
              );
              process.exit(1);
            }
          }
          indexesObject[name2] = {
            name: name2,
            columns: indexColumns,
            isUnique: value.config.unique ?? false,
            using: value.config.using,
            algorithm: value.config.algorythm,
            lock: value.config.lock
          };
        });
        if (!schema5) {
          result[tableName] = {
            name: tableName,
            columns: columnsObject,
            indexes: indexesObject,
            compositePrimaryKeys: primaryKeysObject,
            uniqueConstraints: uniqueConstraintObject
          };
        }
      }
      return {
        version: "1",
        dialect: "singlestore",
        tables: result,
        /* views: resultViews, */
        _meta: {
          tables: {},
          columns: {}
        },
        internal
      };
    };
    fromDatabase4 = async (db, inputSchema, tablesFilter = (table6) => true, progressCallback) => {
      const result = {};
      const internals = { tables: {}, indexes: {} };
      const columns = await db.query(`select * from information_schema.columns
	where table_schema = '${inputSchema}' and table_name != '__drizzle_migrations'
	order by table_name, ordinal_position;`);
      const response = columns;
      const schemas = [];
      let columnsCount = 0;
      let tablesCount = /* @__PURE__ */ new Set();
      let indexesCount = 0;
      const idxs = await db.query(
        `select * from INFORMATION_SCHEMA.STATISTICS
	WHERE INFORMATION_SCHEMA.STATISTICS.TABLE_SCHEMA = '${inputSchema}' and INFORMATION_SCHEMA.STATISTICS.INDEX_NAME != 'PRIMARY';`
      );
      const idxRows = idxs;
      for (const column6 of response) {
        if (!tablesFilter(column6["TABLE_NAME"])) continue;
        columnsCount += 1;
        if (progressCallback) {
          progressCallback("columns", columnsCount, "fetching");
        }
        const schema5 = column6["TABLE_SCHEMA"];
        const tableName = column6["TABLE_NAME"];
        tablesCount.add(`${schema5}.${tableName}`);
        if (progressCallback) {
          progressCallback("columns", tablesCount.size, "fetching");
        }
        const columnName = column6["COLUMN_NAME"];
        const isNullable = column6["IS_NULLABLE"] === "YES";
        const dataType = column6["DATA_TYPE"];
        const columnType = column6["COLUMN_TYPE"];
        const isPrimary = column6["COLUMN_KEY"] === "PRI";
        let columnDefault = column6["COLUMN_DEFAULT"];
        const collation = column6["CHARACTER_SET_NAME"];
        const geenratedExpression = column6["GENERATION_EXPRESSION"];
        let columnExtra = column6["EXTRA"];
        let isAutoincrement = false;
        let isDefaultAnExpression = false;
        if (typeof column6["EXTRA"] !== "undefined") {
          columnExtra = column6["EXTRA"];
          isAutoincrement = column6["EXTRA"] === "auto_increment";
          isDefaultAnExpression = column6["EXTRA"].includes("DEFAULT_GENERATED");
        }
        if (schema5 !== inputSchema) {
          schemas.push(schema5);
        }
        const table6 = result[tableName];
        let changedType = columnType;
        if (columnType === "bigint unsigned" && !isNullable && isAutoincrement) {
          const uniqueIdx = idxRows.filter(
            (it) => it["COLUMN_NAME"] === columnName && it["TABLE_NAME"] === tableName && it["NON_UNIQUE"] === 0
          );
          if (uniqueIdx && uniqueIdx.length === 1) {
            changedType = columnType.replace("bigint unsigned", "serial");
          }
        }
        if (columnType.startsWith("bigint(") || columnType.startsWith("tinyint(") || columnType.startsWith("date(") || columnType.startsWith("int(") || columnType.startsWith("mediumint(") || columnType.startsWith("smallint(") || columnType.startsWith("text(") || columnType.startsWith("time(") || columnType.startsWith("year(")) {
          changedType = columnType.replace(/\(\s*[^)]*\)$/, "");
        }
        if (columnType.includes("decimal(10,0)")) {
          changedType = columnType.replace("decimal(10,0)", "decimal");
        }
        if (columnDefault?.endsWith(".")) {
          columnDefault = columnDefault.slice(0, -1);
        }
        let onUpdate = void 0;
        if (columnType.startsWith("timestamp") && typeof columnExtra !== "undefined" && columnExtra.includes("on update CURRENT_TIMESTAMP")) {
          onUpdate = true;
        }
        const newColumn = {
          default: columnDefault === null ? void 0 : /^-?[\d.]+(?:e-?\d+)?$/.test(columnDefault) && !["decimal", "char", "varchar"].some((type) => columnType.startsWith(type)) ? Number(columnDefault) : isDefaultAnExpression ? clearDefaults2(columnDefault, collation) : columnDefault.startsWith("CURRENT_TIMESTAMP") ? "CURRENT_TIMESTAMP" : `'${columnDefault}'`,
          autoincrement: isAutoincrement,
          name: columnName,
          type: changedType,
          primaryKey: false,
          notNull: !isNullable,
          onUpdate,
          generated: geenratedExpression ? {
            as: geenratedExpression,
            type: columnExtra === "VIRTUAL GENERATED" ? "virtual" : "stored"
          } : void 0
        };
        if (isDefaultAnExpression) {
          if (typeof internals.tables[tableName] === "undefined") {
            internals.tables[tableName] = {
              columns: {
                [columnName]: {
                  isDefaultAnExpression: true
                }
              }
            };
          } else {
            if (typeof internals.tables[tableName].columns[columnName] === "undefined") {
              internals.tables[tableName].columns[columnName] = {
                isDefaultAnExpression: true
              };
            } else {
              internals.tables[tableName].columns[columnName].isDefaultAnExpression = true;
            }
          }
        }
        if (!table6) {
          result[tableName] = {
            name: tableName,
            columns: {
              [columnName]: newColumn
            },
            compositePrimaryKeys: {},
            indexes: {},
            uniqueConstraints: {}
          };
        } else {
          result[tableName].columns[columnName] = newColumn;
        }
      }
      const tablePks = await db.query(
        `SELECT table_name, column_name, ordinal_position
  FROM information_schema.table_constraints t
  LEFT JOIN information_schema.key_column_usage k
  USING(constraint_name,table_schema,table_name)
  WHERE t.constraint_type='UNIQUE'
      and table_name != '__drizzle_migrations'
      AND t.table_schema = '${inputSchema}'
      ORDER BY ordinal_position`
      );
      const tableToPk = {};
      const tableToPkRows = tablePks;
      for (const tableToPkRow of tableToPkRows) {
        const tableName = tableToPkRow["table_name"];
        const columnName = tableToPkRow["column_name"];
        const position = tableToPkRow["ordinal_position"];
        if (typeof result[tableName] === "undefined") {
          continue;
        }
        if (typeof tableToPk[tableName] === "undefined") {
          tableToPk[tableName] = [columnName];
        } else {
          tableToPk[tableName].push(columnName);
        }
      }
      for (const [key, value] of Object.entries(tableToPk)) {
        result[key].compositePrimaryKeys = {
          [`${key}_${value.join("_")}`]: {
            name: `${key}_${value.join("_")}`,
            columns: value
          }
        };
      }
      if (progressCallback) {
        progressCallback("columns", columnsCount, "done");
        progressCallback("tables", tablesCount.size, "done");
      }
      for (const idxRow of idxRows) {
        const tableSchema = idxRow["TABLE_SCHEMA"];
        const tableName = idxRow["TABLE_NAME"];
        const constraintName = idxRow["INDEX_NAME"];
        const columnName = idxRow["COLUMN_NAME"];
        const isUnique = idxRow["NON_UNIQUE"] === 0;
        const tableInResult = result[tableName];
        if (typeof tableInResult === "undefined") continue;
        indexesCount += 1;
        if (progressCallback) {
          progressCallback("indexes", indexesCount, "fetching");
        }
        if (isUnique) {
          if (typeof tableInResult.uniqueConstraints[constraintName] !== "undefined") {
            tableInResult.uniqueConstraints[constraintName].columns.push(
              columnName
            );
          } else {
            tableInResult.uniqueConstraints[constraintName] = {
              name: constraintName,
              columns: [columnName]
            };
          }
        }
      }
      if (progressCallback) {
        progressCallback("indexes", indexesCount, "done");
        progressCallback("enums", 0, "done");
      }
      return {
        version: "1",
        dialect: "singlestore",
        tables: result,
        /* views: resultViews, */
        _meta: {
          tables: {},
          columns: {}
        },
        internal: internals
      };
    };
  }
});

// src/serializer/sqliteImports.ts
var sqliteImports_exports = {};
__export(sqliteImports_exports, {
  prepareFromExports: () => prepareFromExports2,
  prepareFromSqliteImports: () => prepareFromSqliteImports
});
var prepareFromExports2, prepareFromSqliteImports;
var init_sqliteImports = __esm({
  "src/serializer/sqliteImports.ts"() {
    "use strict";
    init_dist();
    init_sqlite_core();
    init_utils9();
    prepareFromExports2 = (exports) => {
      const tables = [];
      const views = [];
      const i0values = Object.values(exports);
      i0values.forEach((t) => {
        if (is(t, SQLiteTable)) {
          tables.push(t);
        }
        if (is(t, SQLiteView2)) {
          views.push(t);
        }
      });
      return { tables, views };
    };
    prepareFromSqliteImports = async (imports) => {
      const tables = [];
      const views = [];
      const { unregister } = await safeRegister();
      for (let i = 0; i < imports.length; i++) {
        const it = imports[i];
        const i0 = __require(`${it}`);
        const prepared = prepareFromExports2(i0);
        tables.push(...prepared.tables);
        views.push(...prepared.views);
      }
      unregister();
      return { tables: Array.from(new Set(tables)), views };
    };
  }
});

// src/serializer/mysqlImports.ts
var mysqlImports_exports = {};
__export(mysqlImports_exports, {
  prepareFromExports: () => prepareFromExports3,
  prepareFromMySqlImports: () => prepareFromMySqlImports
});
var prepareFromExports3, prepareFromMySqlImports;
var init_mysqlImports = __esm({
  "src/serializer/mysqlImports.ts"() {
    "use strict";
    init_dist();
    init_mysql_core();
    init_utils9();
    prepareFromExports3 = (exports) => {
      const tables = [];
      const views = [];
      const i0values = Object.values(exports);
      i0values.forEach((t) => {
        if (is(t, MySqlTable)) {
          tables.push(t);
        }
        if (is(t, MySqlView2)) {
          views.push(t);
        }
      });
      return { tables, views };
    };
    prepareFromMySqlImports = async (imports) => {
      const tables = [];
      const views = [];
      const { unregister } = await safeRegister();
      for (let i = 0; i < imports.length; i++) {
        const it = imports[i];
        const i0 = __require(`${it}`);
        const prepared = prepareFromExports3(i0);
        tables.push(...prepared.tables);
        views.push(...prepared.views);
      }
      unregister();
      return { tables: Array.from(new Set(tables)), views };
    };
  }
});

// src/cli/commands/mysqlPushUtils.ts
var mysqlPushUtils_exports = {};
__export(mysqlPushUtils_exports, {
  filterStatements: () => filterStatements,
  logSuggestionsAndReturn: () => logSuggestionsAndReturn2
});
var import_hanji8, filterStatements, logSuggestionsAndReturn2;
var init_mysqlPushUtils = __esm({
  "src/cli/commands/mysqlPushUtils.ts"() {
    "use strict";
    init_source();
    import_hanji8 = __toESM(require_hanji());
    init_mysqlSchema();
    init_selector_ui();
    init_outputs();
    filterStatements = (statements, currentSchema, prevSchema) => {
      return statements.filter((statement) => {
        if (statement.type === "alter_table_alter_column_set_type") {
          if (statement.oldDataType.startsWith("tinyint") && statement.newDataType.startsWith("boolean")) {
            return false;
          }
          if (statement.oldDataType.startsWith("bigint unsigned") && statement.newDataType.startsWith("serial")) {
            return false;
          }
          if (statement.oldDataType.startsWith("serial") && statement.newDataType.startsWith("bigint unsigned")) {
            return false;
          }
        } else if (statement.type === "alter_table_alter_column_set_default") {
          if (statement.newDefaultValue === false && statement.oldDefaultValue === 0 && statement.newDataType === "boolean") {
            return false;
          }
          if (statement.newDefaultValue === true && statement.oldDefaultValue === 1 && statement.newDataType === "boolean") {
            return false;
          }
        } else if (statement.type === "delete_unique_constraint") {
          const unsquashed = MySqlSquasher.unsquashUnique(statement.data);
          if (unsquashed.columns.length === 1 && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && prevSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].name === unsquashed.columns[0]) {
            return false;
          }
        } else if (statement.type === "alter_table_alter_column_drop_notnull") {
          const serialStatement = statements.find(
            (it) => it.type === "alter_table_alter_column_set_type"
          );
          if (serialStatement?.oldDataType.startsWith("bigint unsigned") && serialStatement?.newDataType.startsWith("serial") && serialStatement.columnName === statement.columnName && serialStatement.tableName === statement.tableName) {
            return false;
          }
          if (statement.newDataType === "serial" && !statement.columnNotNull) {
            return false;
          }
          if (statement.columnAutoIncrement) {
            return false;
          }
        }
        return true;
      });
    };
    logSuggestionsAndReturn2 = async (db, statements, json22) => {
      let shouldAskForApprove = false;
      const statementsToExecute = [];
      const infoToPrint = [];
      const tablesToRemove = [];
      const columnsToRemove = [];
      const schemasToRemove = [];
      const tablesToTruncate = [];
      for (const statement of statements) {
        if (statement.type === "drop_table") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count2 = Number(res[0].count);
          if (count2 > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.tableName
              )} table with ${count2} items`
            );
            tablesToRemove.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_drop_column") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count2 = Number(res[0].count);
          if (count2 > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.columnName
              )} column in ${statement.tableName} table with ${count2} items`
            );
            columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "drop_schema") {
          const res = await db.query(
            `select count(*) as count from information_schema.tables where table_schema = \`${statement.name}\`;`
          );
          const count2 = Number(res[0].count);
          if (count2 > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.name
              )} schema with ${count2} tables`
            );
            schemasToRemove.push(statement.name);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_alter_column_set_type") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count2 = Number(res[0].count);
          if (count2 > 0) {
            infoToPrint.push(
              `\xB7 You're about to change ${source_default.underline(
                statement.columnName
              )} column type from ${source_default.underline(
                statement.oldDataType
              )} to ${source_default.underline(statement.newDataType)} with ${count2} items`
            );
            statementsToExecute.push(`truncate table ${statement.tableName};`);
            tablesToTruncate.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_alter_column_drop_default") {
          if (statement.columnNotNull) {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count2 = Number(res[0].count);
            if (count2 > 0) {
              infoToPrint.push(
                `\xB7 You're about to remove default value from ${source_default.underline(
                  statement.columnName
                )} not-null column with ${count2} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "alter_table_alter_column_set_notnull") {
          if (typeof statement.columnDefault === "undefined") {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count2 = Number(res[0].count);
            if (count2 > 0) {
              infoToPrint.push(
                `\xB7 You're about to set not-null constraint to ${source_default.underline(
                  statement.columnName
                )} column without default, which contains ${count2} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "alter_table_alter_column_drop_pk") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          if (Object.values(json22.tables[statement.tableName].columns).filter(
            (column6) => column6.autoincrement
          ).length > 0) {
            console.log(
              `${withStyle.errorWarning(
                `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
              )}`
            );
            process.exit(1);
          }
          const count2 = Number(res[0].count);
          if (count2 > 0) {
            infoToPrint.push(
              `\xB7 You're about to change ${source_default.underline(
                statement.tableName
              )} primary key. This statements may fail and you table may left without primary key`
            );
            tablesToTruncate.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "delete_composite_pk") {
          if (Object.values(json22.tables[statement.tableName].columns).filter(
            (column6) => column6.autoincrement
          ).length > 0) {
            console.log(
              `${withStyle.errorWarning(
                `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
              )}`
            );
            process.exit(1);
          }
        } else if (statement.type === "alter_table_add_column") {
          if (statement.column.notNull && typeof statement.column.default === "undefined") {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count2 = Number(res[0].count);
            if (count2 > 0) {
              infoToPrint.push(
                `\xB7 You're about to add not-null ${source_default.underline(
                  statement.column.name
                )} column without default value, which contains ${count2} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "create_unique_constraint") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count2 = Number(res[0].count);
          if (count2 > 0) {
            const unsquashedUnique = MySqlSquasher.unsquashUnique(statement.data);
            console.log(
              `\xB7 You're about to add ${source_default.underline(
                unsquashedUnique.name
              )} unique constraint to the table, which contains ${count2} items. If this statement fails, you will receive an error from the database. Do you want to truncate ${source_default.underline(
                statement.tableName
              )} table?
`
            );
            const { status, data } = await (0, import_hanji8.render)(
              new Select([
                "No, add the constraint without truncating the table",
                `Yes, truncate the table`
              ])
            );
            if (data?.index === 1) {
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        }
      }
      return {
        statementsToExecute,
        shouldAskForApprove,
        infoToPrint,
        columnsToRemove: [...new Set(columnsToRemove)],
        schemasToRemove: [...new Set(schemasToRemove)],
        tablesToTruncate: [...new Set(tablesToTruncate)],
        tablesToRemove: [...new Set(tablesToRemove)]
      };
    };
  }
});

// src/cli/commands/mysqlIntrospect.ts
var mysqlIntrospect_exports = {};
__export(mysqlIntrospect_exports, {
  mysqlPushIntrospect: () => mysqlPushIntrospect
});
var import_hanji9, mysqlPushIntrospect;
var init_mysqlIntrospect = __esm({
  "src/cli/commands/mysqlIntrospect.ts"() {
    "use strict";
    import_hanji9 = __toESM(require_hanji());
    init_mjs();
    init_global();
    init_mysqlSerializer();
    init_views();
    mysqlPushIntrospect = async (db, databaseName, filters) => {
      const matchers = filters.map((it) => {
        return new Minimatch(it);
      });
      const filter2 = (tableName) => {
        if (matchers.length === 0) return true;
        let flags = [];
        for (let matcher of matchers) {
          if (matcher.negate) {
            if (!matcher.match(tableName)) {
              flags.push(false);
            }
          }
          if (matcher.match(tableName)) {
            flags.push(true);
          }
        }
        if (flags.length > 0) {
          return flags.every(Boolean);
        }
        return false;
      };
      const progress = new ProgressView(
        "Pulling schema from database...",
        "Pulling schema from database..."
      );
      const res = await (0, import_hanji9.renderWithTask)(
        progress,
        fromDatabase3(db, databaseName, filter2)
      );
      const schema5 = { id: originUUID, prevId: "", ...res };
      const { internal, ...schemaWithoutInternals } = schema5;
      return { schema: schemaWithoutInternals };
    };
  }
});

// src/serializer/singlestoreImports.ts
var singlestoreImports_exports = {};
__export(singlestoreImports_exports, {
  prepareFromExports: () => prepareFromExports4,
  prepareFromSingleStoreImports: () => prepareFromSingleStoreImports
});
var prepareFromExports4, prepareFromSingleStoreImports;
var init_singlestoreImports = __esm({
  "src/serializer/singlestoreImports.ts"() {
    "use strict";
    init_dist();
    init_singlestore_core();
    init_utils9();
    prepareFromExports4 = (exports) => {
      const tables = [];
      const i0values = Object.values(exports);
      i0values.forEach((t) => {
        if (is(t, SingleStoreTable)) {
          tables.push(t);
        }
      });
      return {
        tables
        /* views  */
      };
    };
    prepareFromSingleStoreImports = async (imports) => {
      const tables = [];
      const { unregister } = await safeRegister();
      for (let i = 0; i < imports.length; i++) {
        const it = imports[i];
        const i0 = __require(`${it}`);
        const prepared = prepareFromExports4(i0);
        tables.push(...prepared.tables);
      }
      unregister();
      return {
        tables: Array.from(new Set(tables))
        /* , views */
      };
    };
  }
});

// src/cli/commands/singlestorePushUtils.ts
var singlestorePushUtils_exports = {};
__export(singlestorePushUtils_exports, {
  filterStatements: () => filterStatements2,
  findColumnTypeAlternations: () => findColumnTypeAlternations,
  logSuggestionsAndReturn: () => logSuggestionsAndReturn3
});
function findColumnTypeAlternations(columns1, columns2) {
  const changes = [];
  for (const key in columns1) {
    if (columns1.hasOwnProperty(key) && columns2.hasOwnProperty(key)) {
      const col1 = columns1[key];
      const col2 = columns2[key];
      if (col1.type !== col2.type) {
        changes.push(col2.name);
      }
    }
  }
  return changes;
}
var import_hanji10, filterStatements2, logSuggestionsAndReturn3;
var init_singlestorePushUtils = __esm({
  "src/cli/commands/singlestorePushUtils.ts"() {
    "use strict";
    init_source();
    import_hanji10 = __toESM(require_hanji());
    init_sqlgenerator();
    init_singlestoreSchema();
    init_utils();
    init_selector_ui();
    init_outputs();
    filterStatements2 = (statements, currentSchema, prevSchema) => {
      return statements.filter((statement) => {
        if (statement.type === "alter_table_alter_column_set_type") {
          if (statement.oldDataType.startsWith("tinyint") && statement.newDataType.startsWith("boolean")) {
            return false;
          }
          if (statement.oldDataType.startsWith("bigint unsigned") && statement.newDataType.startsWith("serial")) {
            return false;
          }
          if (statement.oldDataType.startsWith("serial") && statement.newDataType.startsWith("bigint unsigned")) {
            return false;
          }
        } else if (statement.type === "alter_table_alter_column_set_default") {
          if (statement.newDefaultValue === false && statement.oldDefaultValue === 0 && statement.newDataType === "boolean") {
            return false;
          }
          if (statement.newDefaultValue === true && statement.oldDefaultValue === 1 && statement.newDataType === "boolean") {
            return false;
          }
        } else if (statement.type === "delete_unique_constraint") {
          const unsquashed = SingleStoreSquasher.unsquashUnique(statement.data);
          if (unsquashed.columns.length === 1 && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && prevSchema.tables[statement.tableName].columns[unsquashed.columns[0]].type === "serial" && currentSchema.tables[statement.tableName].columns[unsquashed.columns[0]].name === unsquashed.columns[0]) {
            return false;
          }
        } else if (statement.type === "alter_table_alter_column_drop_notnull") {
          const serialStatement = statements.find(
            (it) => it.type === "alter_table_alter_column_set_type"
          );
          if (serialStatement?.oldDataType.startsWith("bigint unsigned") && serialStatement?.newDataType.startsWith("serial") && serialStatement.columnName === statement.columnName && serialStatement.tableName === statement.tableName) {
            return false;
          }
          if (statement.newDataType === "serial" && !statement.columnNotNull) {
            return false;
          }
          if (statement.columnAutoIncrement) {
            return false;
          }
        }
        return true;
      });
    };
    logSuggestionsAndReturn3 = async (db, statements, json22, json1) => {
      let shouldAskForApprove = false;
      const statementsToExecute = [];
      const infoToPrint = [];
      const tablesToRemove = [];
      const columnsToRemove = [];
      const schemasToRemove = [];
      const tablesToTruncate = [];
      for (const statement of statements) {
        if (statement.type === "drop_table") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count2 = Number(res[0].count);
          if (count2 > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.tableName
              )} table with ${count2} items`
            );
            tablesToRemove.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_drop_column") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count2 = Number(res[0].count);
          if (count2 > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.columnName
              )} column in ${statement.tableName} table with ${count2} items`
            );
            columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "drop_schema") {
          const res = await db.query(
            `select count(*) as count from information_schema.tables where table_schema = \`${statement.name}\`;`
          );
          const count2 = Number(res[0].count);
          if (count2 > 0) {
            infoToPrint.push(
              `\xB7 You're about to delete ${source_default.underline(
                statement.name
              )} schema with ${count2} tables`
            );
            schemasToRemove.push(statement.name);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_alter_column_set_type") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count2 = Number(res[0].count);
          if (count2 > 0) {
            infoToPrint.push(
              `\xB7 You're about to change ${source_default.underline(
                statement.columnName
              )} column type from ${source_default.underline(
                statement.oldDataType
              )} to ${source_default.underline(statement.newDataType)} with ${count2} items`
            );
            statementsToExecute.push(`truncate table ${statement.tableName};`);
            tablesToTruncate.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "alter_table_alter_column_drop_default") {
          if (statement.columnNotNull) {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count2 = Number(res[0].count);
            if (count2 > 0) {
              infoToPrint.push(
                `\xB7 You're about to remove default value from ${source_default.underline(
                  statement.columnName
                )} not-null column with ${count2} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "alter_table_alter_column_set_notnull") {
          if (typeof statement.columnDefault === "undefined") {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count2 = Number(res[0].count);
            if (count2 > 0) {
              infoToPrint.push(
                `\xB7 You're about to set not-null constraint to ${source_default.underline(
                  statement.columnName
                )} column without default, which contains ${count2} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "alter_table_alter_column_drop_pk") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          if (Object.values(json22.tables[statement.tableName].columns).filter(
            (column6) => column6.autoincrement
          ).length > 0) {
            console.log(
              `${withStyle.errorWarning(
                `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
              )}`
            );
            process.exit(1);
          }
          const count2 = Number(res[0].count);
          if (count2 > 0) {
            infoToPrint.push(
              `\xB7 You're about to change ${source_default.underline(
                statement.tableName
              )} primary key. This statements may fail and you table may left without primary key`
            );
            tablesToTruncate.push(statement.tableName);
            shouldAskForApprove = true;
          }
        } else if (statement.type === "delete_composite_pk") {
          if (Object.values(json22.tables[statement.tableName].columns).filter(
            (column6) => column6.autoincrement
          ).length > 0) {
            console.log(
              `${withStyle.errorWarning(
                `You have removed the primary key from a ${statement.tableName} table without removing the auto-increment property from this table. As the database error states: 'there can be only one auto column, and it must be defined as a key. Make sure to remove autoincrement from ${statement.tableName} table`
              )}`
            );
            process.exit(1);
          }
        } else if (statement.type === "alter_table_add_column") {
          if (statement.column.notNull && typeof statement.column.default === "undefined") {
            const res = await db.query(
              `select count(*) as count from \`${statement.tableName}\``
            );
            const count2 = Number(res[0].count);
            if (count2 > 0) {
              infoToPrint.push(
                `\xB7 You're about to add not-null ${source_default.underline(
                  statement.column.name
                )} column without default value, which contains ${count2} items`
              );
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "create_unique_constraint") {
          const res = await db.query(
            `select count(*) as count from \`${statement.tableName}\``
          );
          const count2 = Number(res[0].count);
          if (count2 > 0) {
            const unsquashedUnique = SingleStoreSquasher.unsquashUnique(statement.data);
            console.log(
              `\xB7 You're about to add ${source_default.underline(
                unsquashedUnique.name
              )} unique constraint to the table, which contains ${count2} items. If this statement fails, you will receive an error from the database. Do you want to truncate ${source_default.underline(
                statement.tableName
              )} table?
`
            );
            const { status, data } = await (0, import_hanji10.render)(
              new Select([
                "No, add the constraint without truncating the table",
                `Yes, truncate the table`
              ])
            );
            if (data?.index === 1) {
              tablesToTruncate.push(statement.tableName);
              statementsToExecute.push(`truncate table ${statement.tableName};`);
              shouldAskForApprove = true;
            }
          }
        } else if (statement.type === "singlestore_recreate_table") {
          const tableName = statement.tableName;
          const prevColumns = json1.tables[tableName].columns;
          const currentColumns = json22.tables[tableName].columns;
          const { removedColumns, addedColumns } = findAddedAndRemoved(
            Object.keys(prevColumns),
            Object.keys(currentColumns)
          );
          if (removedColumns.length) {
            for (const removedColumn of removedColumns) {
              const res = await db.query(
                `select count(\`${tableName}\`.\`${removedColumn}\`) as count from \`${tableName}\``
              );
              const count2 = Number(res[0].count);
              if (count2 > 0) {
                infoToPrint.push(
                  `\xB7 You're about to delete ${source_default.underline(
                    removedColumn
                  )} column in ${tableName} table with ${count2} items`
                );
                columnsToRemove.push(removedColumn);
                shouldAskForApprove = true;
              }
            }
          }
          if (addedColumns.length) {
            for (const addedColumn of addedColumns) {
              const [res] = await db.query(
                `select count(*) as count from \`${tableName}\``
              );
              const columnConf = json22.tables[tableName].columns[addedColumn];
              const count2 = Number(res.count);
              if (count2 > 0 && columnConf.notNull && !columnConf.default) {
                infoToPrint.push(
                  `\xB7 You're about to add not-null ${source_default.underline(
                    addedColumn
                  )} column without default value to table, which contains ${count2} items`
                );
                shouldAskForApprove = true;
                tablesToTruncate.push(tableName);
                statementsToExecute.push(`TRUNCATE TABLE \`${tableName}\`;`);
              }
            }
          }
          const columnWithChangedType = findColumnTypeAlternations(prevColumns, currentColumns);
          for (const column6 of columnWithChangedType) {
            const [res] = await db.query(
              `select count(*) as count from \`${tableName}\` WHERE \`${tableName}\`.\`${column6}\` IS NOT NULL;`
            );
            const count2 = Number(res.count);
            if (count2 > 0) {
              infoToPrint.push(
                `\xB7 You're about recreate ${source_default.underline(tableName)} table with data type changing for ${source_default.underline(
                  column6
                )} column, which contains ${count2} items`
              );
              shouldAskForApprove = true;
              tablesToTruncate.push(tableName);
              statementsToExecute.push(`TRUNCATE TABLE \`${tableName}\`;`);
            }
          }
        }
        const stmnt = fromJson([statement], "singlestore", "push");
        if (typeof stmnt !== "undefined") {
          statementsToExecute.push(...stmnt);
        }
      }
      return {
        statementsToExecute,
        shouldAskForApprove,
        infoToPrint,
        columnsToRemove: [...new Set(columnsToRemove)],
        schemasToRemove: [...new Set(schemasToRemove)],
        tablesToTruncate: [...new Set(tablesToTruncate)],
        tablesToRemove: [...new Set(tablesToRemove)]
      };
    };
  }
});

// src/cli/commands/singlestoreIntrospect.ts
var singlestoreIntrospect_exports = {};
__export(singlestoreIntrospect_exports, {
  singlestorePushIntrospect: () => singlestorePushIntrospect
});
var import_hanji11, singlestorePushIntrospect;
var init_singlestoreIntrospect = __esm({
  "src/cli/commands/singlestoreIntrospect.ts"() {
    "use strict";
    import_hanji11 = __toESM(require_hanji());
    init_mjs();
    init_global();
    init_singlestoreSerializer();
    init_views();
    singlestorePushIntrospect = async (db, databaseName, filters) => {
      const matchers = filters.map((it) => {
        return new Minimatch(it);
      });
      const filter2 = (tableName) => {
        if (matchers.length === 0) return true;
        let flags = [];
        for (let matcher of matchers) {
          if (matcher.negate) {
            if (!matcher.match(tableName)) {
              flags.push(false);
            }
          }
          if (matcher.match(tableName)) {
            flags.push(true);
          }
        }
        if (flags.length > 0) {
          return flags.every(Boolean);
        }
        return false;
      };
      const progress = new ProgressView(
        "Pulling schema from database...",
        "Pulling schema from database..."
      );
      const res = await (0, import_hanji11.renderWithTask)(
        progress,
        fromDatabase4(db, databaseName, filter2)
      );
      const schema5 = { id: originUUID, prevId: "", ...res };
      const { internal, ...schemaWithoutInternals } = schema5;
      return { schema: schemaWithoutInternals };
    };
  }
});

// src/api.ts
init_migrate();
import { randomUUID } from "crypto";

// src/cli/commands/pgIntrospect.ts
var import_hanji3 = __toESM(require_hanji());
init_mjs();
init_global();
init_pgSerializer();
init_views();
var pgPushIntrospect = async (db, filters, schemaFilters, entities, tsSchema) => {
  const matchers = filters.map((it) => {
    return new Minimatch(it);
  });
  const filter2 = (tableName) => {
    if (matchers.length === 0) return true;
    let flags = [];
    for (let matcher of matchers) {
      if (matcher.negate) {
        if (!matcher.match(tableName)) {
          flags.push(false);
        }
      }
      if (matcher.match(tableName)) {
        flags.push(true);
      }
    }
    if (flags.length > 0) {
      return flags.every(Boolean);
    }
    return false;
  };
  const progress = new ProgressView(
    "Pulling schema from database...",
    "Pulling schema from database..."
  );
  const res = await (0, import_hanji3.renderWithTask)(
    progress,
    fromDatabase(db, filter2, schemaFilters, entities, void 0, tsSchema)
  );
  const schema5 = { id: originUUID, prevId: "", ...res };
  const { internal, ...schemaWithoutInternals } = schema5;
  return { schema: schemaWithoutInternals };
};

// src/cli/commands/pgPushUtils.ts
init_source();
var import_hanji5 = __toESM(require_hanji());
init_pgSchema();
init_sqlgenerator();
init_selector_ui();
function concatSchemaAndTableName(schema5, table6) {
  return schema5 ? `"${schema5}"."${table6}"` : `"${table6}"`;
}
function tableNameWithSchemaFrom(schema5, tableName, renamedSchemas, renamedTables) {
  const newSchemaName = schema5 ? renamedSchemas[schema5] ? renamedSchemas[schema5] : schema5 : void 0;
  const newTableName = renamedTables[concatSchemaAndTableName(newSchemaName, tableName)] ? renamedTables[concatSchemaAndTableName(newSchemaName, tableName)] : tableName;
  return concatSchemaAndTableName(newSchemaName, newTableName);
}
var pgSuggestions = async (db, statements) => {
  let shouldAskForApprove = false;
  const statementsToExecute = [];
  const infoToPrint = [];
  const tablesToRemove = [];
  const columnsToRemove = [];
  const schemasToRemove = [];
  const tablesToTruncate = [];
  const matViewsToRemove = [];
  let renamedSchemas = {};
  let renamedTables = {};
  for (const statement of statements) {
    if (statement.type === "rename_schema") {
      renamedSchemas[statement.to] = statement.from;
    } else if (statement.type === "rename_table") {
      renamedTables[concatSchemaAndTableName(statement.toSchema, statement.tableNameTo)] = statement.tableNameFrom;
    } else if (statement.type === "drop_table") {
      const res = await db.query(
        `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
      );
      const count2 = Number(res[0].count);
      if (count2 > 0) {
        infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.tableName)} table with ${count2} items`);
        tablesToRemove.push(statement.tableName);
        shouldAskForApprove = true;
      }
    } else if (statement.type === "drop_view" && statement.materialized) {
      const res = await db.query(`select count(*) as count from "${statement.schema ?? "public"}"."${statement.name}"`);
      const count2 = Number(res[0].count);
      if (count2 > 0) {
        infoToPrint.push(
          `\xB7 You're about to delete "${source_default.underline(statement.name)}" materialized view with ${count2} items`
        );
        matViewsToRemove.push(statement.name);
        shouldAskForApprove = true;
      }
    } else if (statement.type === "alter_table_drop_column") {
      const res = await db.query(
        `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
      );
      const count2 = Number(res[0].count);
      if (count2 > 0) {
        infoToPrint.push(
          `\xB7 You're about to delete ${source_default.underline(statement.columnName)} column in ${statement.tableName} table with ${count2} items`
        );
        columnsToRemove.push(`${statement.tableName}_${statement.columnName}`);
        shouldAskForApprove = true;
      }
    } else if (statement.type === "drop_schema") {
      const res = await db.query(
        `select count(*) as count from information_schema.tables where table_schema = '${statement.name}';`
      );
      const count2 = Number(res[0].count);
      if (count2 > 0) {
        infoToPrint.push(`\xB7 You're about to delete ${source_default.underline(statement.name)} schema with ${count2} tables`);
        schemasToRemove.push(statement.name);
        shouldAskForApprove = true;
      }
    } else if (statement.type === "alter_table_alter_column_set_type") {
      const res = await db.query(
        `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
      );
      const count2 = Number(res[0].count);
      if (count2 > 0) {
        infoToPrint.push(
          `\xB7 You're about to change ${source_default.underline(statement.columnName)} column type from ${source_default.underline(statement.oldDataType)} to ${source_default.underline(
            statement.newDataType
          )} with ${count2} items`
        );
        statementsToExecute.push(
          `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
        );
        tablesToTruncate.push(statement.tableName);
        shouldAskForApprove = true;
      }
    } else if (statement.type === "alter_table_alter_column_drop_pk") {
      const res = await db.query(
        `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
      );
      const count2 = Number(res[0].count);
      if (count2 > 0) {
        infoToPrint.push(
          `\xB7 You're about to change ${source_default.underline(statement.tableName)} primary key. This statements may fail and you table may left without primary key`
        );
        tablesToTruncate.push(statement.tableName);
        shouldAskForApprove = true;
      }
      const tableNameWithSchema = tableNameWithSchemaFrom(
        statement.schema,
        statement.tableName,
        renamedSchemas,
        renamedTables
      );
      const pkNameResponse = await db.query(
        `SELECT constraint_name FROM information_schema.table_constraints
        WHERE table_schema = '${typeof statement.schema === "undefined" || statement.schema === "" ? "public" : statement.schema}'
            AND table_name = '${statement.tableName}'
            AND constraint_type = 'PRIMARY KEY';`
      );
      statementsToExecute.push(
        `ALTER TABLE ${tableNameWithSchema} DROP CONSTRAINT "${pkNameResponse[0].constraint_name}"`
      );
      continue;
    } else if (statement.type === "alter_table_add_column") {
      if (statement.column.notNull && typeof statement.column.default === "undefined") {
        const res = await db.query(
          `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
        );
        const count2 = Number(res[0].count);
        if (count2 > 0) {
          infoToPrint.push(
            `\xB7 You're about to add not-null ${source_default.underline(statement.column.name)} column without default value, which contains ${count2} items`
          );
          tablesToTruncate.push(statement.tableName);
          statementsToExecute.push(
            `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
          );
          shouldAskForApprove = true;
        }
      }
    } else if (statement.type === "create_unique_constraint") {
      const res = await db.query(
        `select count(*) as count from ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)}`
      );
      const count2 = Number(res[0].count);
      if (count2 > 0) {
        const unsquashedUnique = PgSquasher.unsquashUnique(statement.data);
        console.log(
          `\xB7 You're about to add ${source_default.underline(
            unsquashedUnique.name
          )} unique constraint to the table, which contains ${count2} items. If this statement fails, you will receive an error from the database. Do you want to truncate ${source_default.underline(
            statement.tableName
          )} table?
`
        );
        const { status, data } = await (0, import_hanji5.render)(
          new Select(["No, add the constraint without truncating the table", `Yes, truncate the table`])
        );
        if (data?.index === 1) {
          tablesToTruncate.push(statement.tableName);
          statementsToExecute.push(
            `truncate table ${tableNameWithSchemaFrom(statement.schema, statement.tableName, renamedSchemas, renamedTables)} cascade;`
          );
          shouldAskForApprove = true;
        }
      }
    }
    const stmnt = fromJson([statement], "postgresql", "push");
    if (typeof stmnt !== "undefined") {
      statementsToExecute.push(...stmnt);
    }
  }
  return {
    statementsToExecute: [...new Set(statementsToExecute)],
    shouldAskForApprove,
    infoToPrint,
    matViewsToRemove: [...new Set(matViewsToRemove)],
    columnsToRemove: [...new Set(columnsToRemove)],
    schemasToRemove: [...new Set(schemasToRemove)],
    tablesToTruncate: [...new Set(tablesToTruncate)],
    tablesToRemove: [...new Set(tablesToRemove)]
  };
};

// src/cli/commands/pgUp.ts
init_pgSchema();
init_utils();
var updateUpToV6 = (json4) => {
  const schema5 = pgSchemaV5.parse(json4);
  const tables = Object.fromEntries(
    Object.entries(schema5.tables).map((it) => {
      const table6 = it[1];
      const schema6 = table6.schema || "public";
      return [`${schema6}.${table6.name}`, table6];
    })
  );
  const enums = Object.fromEntries(
    Object.entries(schema5.enums).map((it) => {
      const en = it[1];
      return [
        `public.${en.name}`,
        {
          name: en.name,
          schema: "public",
          values: Object.values(en.values)
        }
      ];
    })
  );
  return {
    ...schema5,
    version: "6",
    dialect: "postgresql",
    tables,
    enums
  };
};
var updateUpToV7 = (json4) => {
  const schema5 = pgSchemaV6.parse(json4);
  const tables = Object.fromEntries(
    Object.entries(schema5.tables).map((it) => {
      const table6 = it[1];
      const mappedIndexes = Object.fromEntries(
        Object.entries(table6.indexes).map((idx) => {
          const { columns, ...rest } = idx[1];
          const mappedColumns = columns.map((it2) => {
            return {
              expression: it2,
              isExpression: false,
              asc: true,
              nulls: "last",
              opClass: void 0
            };
          });
          return [idx[0], { columns: mappedColumns, with: {}, ...rest }];
        })
      );
      return [it[0], { ...table6, indexes: mappedIndexes, policies: {}, isRLSEnabled: false, checkConstraints: {} }];
    })
  );
  return {
    ...schema5,
    version: "7",
    dialect: "postgresql",
    sequences: {},
    tables,
    policies: {},
    views: {},
    roles: {}
  };
};

// src/cli/commands/sqliteIntrospect.ts
var import_hanji6 = __toESM(require_hanji());
init_mjs();
init_global();

// ../node_modules/.pnpm/camelcase@7.0.1/node_modules/camelcase/index.js
var UPPERCASE = /[\p{Lu}]/u;
var LOWERCASE = /[\p{Ll}]/u;
var LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu;
var IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u;
var SEPARATORS = /[_.\- ]+/;
var LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source);
var SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu");
var NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu");
var preserveCamelCase = (string, toLowerCase, toUpperCase, preserveConsecutiveUppercase2) => {
  let isLastCharLower = false;
  let isLastCharUpper = false;
  let isLastLastCharUpper = false;
  let isLastLastCharPreserved = false;
  for (let index6 = 0; index6 < string.length; index6++) {
    const character = string[index6];
    isLastLastCharPreserved = index6 > 2 ? string[index6 - 3] === "-" : true;
    if (isLastCharLower && UPPERCASE.test(character)) {
      string = string.slice(0, index6) + "-" + string.slice(index6);
      isLastCharLower = false;
      isLastLastCharUpper = isLastCharUpper;
      isLastCharUpper = true;
      index6++;
    } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character) && (!isLastLastCharPreserved || preserveConsecutiveUppercase2)) {
      string = string.slice(0, index6 - 1) + "-" + string.slice(index6 - 1);
      isLastLastCharUpper = isLastCharUpper;
      isLastCharUpper = false;
      isLastCharLower = true;
    } else {
      isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character;
      isLastLastCharUpper = isLastCharUpper;
      isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character;
    }
  }
  return string;
};
var preserveConsecutiveUppercase = (input, toLowerCase) => {
  LEADING_CAPITAL.lastIndex = 0;
  return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1));
};
var postProcess = (input, toUpperCase) => {
  SEPARATORS_AND_IDENTIFIER.lastIndex = 0;
  NUMBERS_AND_IDENTIFIER.lastIndex = 0;
  return input.replace(SEPARATORS_AND_IDENTIFIER, (_2, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m) => toUpperCase(m));
};
function camelCase(input, options) {
  if (!(typeof input === "string" || Array.isArray(input))) {
    throw new TypeError("Expected the input to be `string | string[]`");
  }
  options = {
    pascalCase: false,
    preserveConsecutiveUppercase: false,
    ...options
  };
  if (Array.isArray(input)) {
    input = input.map((x) => x.trim()).filter((x) => x.length).join("-");
  } else {
    input = input.trim();
  }
  if (input.length === 0) {
    return "";
  }
  const toLowerCase = options.locale === false ? (string) => string.toLowerCase() : (string) => string.toLocaleLowerCase(options.locale);
  const toUpperCase = options.locale === false ? (string) => string.toUpperCase() : (string) => string.toLocaleUpperCase(options.locale);
  if (input.length === 1) {
    if (SEPARATORS.test(input)) {
      return "";
    }
    return options.pascalCase ? toUpperCase(input) : toLowerCase(input);
  }
  const hasUpperCase = input !== toLowerCase(input);
  if (hasUpperCase) {
    input = preserveCamelCase(input, toLowerCase, toUpperCase, options.preserveConsecutiveUppercase);
  }
  input = input.replace(LEADING_SEPARATORS, "");
  input = options.preserveConsecutiveUppercase ? preserveConsecutiveUppercase(input, toLowerCase) : toLowerCase(input);
  if (options.pascalCase) {
    input = toUpperCase(input.charAt(0)) + input.slice(1);
  }
  return postProcess(input, toUpperCase);
}

// src/@types/utils.ts
String.prototype.trimChar = function(char4) {
  let start = 0;
  let end = this.length;
  while (start < end && this[start] === char4) ++start;
  while (end > start && this[end - 1] === char4) --end;
  return start > 0 || end < this.length ? this.substring(start, end) : this.toString();
};
String.prototype.squashSpaces = function() {
  return this.replace(/  +/g, " ").trim();
};
String.prototype.camelCase = function() {
  return camelCase(String(this));
};
String.prototype.capitalise = function() {
  return this && this.length > 0 ? `${this[0].toUpperCase()}${this.slice(1)}` : String(this);
};
String.prototype.concatIf = function(it, condition) {
  return condition ? `${this}${it}` : String(this);
};
String.prototype.snake_case = function() {
  return this && this.length > 0 ? `${this.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)}` : String(this);
};
Array.prototype.random = function() {
  return this[~~(Math.random() * this.length)];
};

// src/introspect-sqlite.ts
init_global();

// src/cli/commands/sqliteIntrospect.ts
init_sqliteSerializer();
init_views();
var sqlitePushIntrospect = async (db, filters) => {
  const matchers = filters.map((it) => {
    return new Minimatch(it);
  });
  const filter2 = (tableName) => {
    if (matchers.length === 0) return true;
    let flags = [];
    for (let matcher of matchers) {
      if (matcher.negate) {
        if (!matcher.match(tableName)) {
          flags.push(false);
        }
      }
      if (matcher.match(tableName)) {
        flags.push(true);
      }
    }
    if (flags.length > 0) {
      return flags.every(Boolean);
    }
    return false;
  };
  const progress = new ProgressView(
    "Pulling schema from database...",
    "Pulling schema from database..."
  );
  const res = await (0, import_hanji6.renderWithTask)(progress, fromDatabase2(db, filter2));
  const schema5 = { id: originUUID, prevId: "", ...res };
  return { schema: schema5 };
};

// src/api.ts
init_sqlitePushUtils();
init_getTablesFilterByExtensions();
init_global();
init_migrationPreparator();
init_mysqlSchema();
init_mysqlSerializer();
init_pgImports();
init_pgSchema();
init_pgSerializer();
init_singlestoreSchema();
init_singlestoreSerializer();
init_sqliteSchema();
init_sqliteSerializer();
var generateDrizzleJson = (imports, prevId, schemaFilters, casing2) => {
  const prepared = prepareFromExports(imports);
  const id = randomUUID();
  const snapshot = generatePgSnapshot(
    prepared.tables,
    prepared.enums,
    prepared.schemas,
    prepared.sequences,
    prepared.roles,
    prepared.policies,
    prepared.views,
    prepared.matViews,
    casing2,
    schemaFilters
  );
  return fillPgSnapshot({
    serialized: snapshot,
    id,
    idPrev: prevId ?? originUUID
  });
};
var generateMigration = async (prev, cur) => {
  const { applyPgSnapshotsDiff: applyPgSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const validatedPrev = pgSchema.parse(prev);
  const validatedCur = pgSchema.parse(cur);
  const squashedPrev = squashPgScheme(validatedPrev);
  const squashedCur = squashPgScheme(validatedCur);
  const { sqlStatements, _meta } = await applyPgSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    schemasResolver,
    enumsResolver,
    sequencesResolver,
    policyResolver,
    indPolicyResolver,
    roleResolver,
    tablesResolver,
    columnsResolver,
    viewsResolver,
    validatedPrev,
    validatedCur
  );
  return sqlStatements;
};
var pushSchema = async (imports, drizzleInstance, schemaFilters, tablesFilter, extensionsFilters) => {
  const { applyPgSnapshotsDiff: applyPgSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const { sql: sql2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
  const filters = (tablesFilter ?? []).concat(
    getTablesFilterByExtensions({ extensionsFilters, dialect: "postgresql" })
  );
  const db = {
    query: async (query, params) => {
      const res = await drizzleInstance.execute(sql2.raw(query));
      return res.rows;
    }
  };
  const cur = generateDrizzleJson(imports);
  const { schema: prev } = await pgPushIntrospect(
    db,
    filters,
    schemaFilters ?? ["public"],
    void 0
  );
  const validatedPrev = pgSchema.parse(prev);
  const validatedCur = pgSchema.parse(cur);
  const squashedPrev = squashPgScheme(validatedPrev, "push");
  const squashedCur = squashPgScheme(validatedCur, "push");
  const { statements } = await applyPgSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    schemasResolver,
    enumsResolver,
    sequencesResolver,
    policyResolver,
    indPolicyResolver,
    roleResolver,
    tablesResolver,
    columnsResolver,
    viewsResolver,
    validatedPrev,
    validatedCur,
    "push"
  );
  const { shouldAskForApprove, statementsToExecute, infoToPrint } = await pgSuggestions(db, statements);
  return {
    hasDataLoss: shouldAskForApprove,
    warnings: infoToPrint,
    statementsToExecute,
    apply: async () => {
      for (const dStmnt of statementsToExecute) {
        await db.query(dStmnt);
      }
    }
  };
};
var generateSQLiteDrizzleJson = async (imports, prevId, casing2) => {
  const { prepareFromExports: prepareFromExports5 } = await Promise.resolve().then(() => (init_sqliteImports(), sqliteImports_exports));
  const prepared = prepareFromExports5(imports);
  const id = randomUUID();
  const snapshot = generateSqliteSnapshot(prepared.tables, prepared.views, casing2);
  return {
    ...snapshot,
    id,
    prevId: prevId ?? originUUID
  };
};
var generateSQLiteMigration = async (prev, cur) => {
  const { applySqliteSnapshotsDiff: applySqliteSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const validatedPrev = sqliteSchema.parse(prev);
  const validatedCur = sqliteSchema.parse(cur);
  const squashedPrev = squashSqliteScheme(validatedPrev);
  const squashedCur = squashSqliteScheme(validatedCur);
  const { sqlStatements } = await applySqliteSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    tablesResolver,
    columnsResolver,
    sqliteViewsResolver,
    validatedPrev,
    validatedCur
  );
  return sqlStatements;
};
var pushSQLiteSchema = async (imports, drizzleInstance) => {
  const { applySqliteSnapshotsDiff: applySqliteSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const { sql: sql2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
  const db = {
    query: async (query, params) => {
      const res = drizzleInstance.all(sql2.raw(query));
      return res;
    },
    run: async (query) => {
      return Promise.resolve(drizzleInstance.run(sql2.raw(query))).then(
        () => {
        }
      );
    }
  };
  const cur = await generateSQLiteDrizzleJson(imports);
  const { schema: prev } = await sqlitePushIntrospect(db, []);
  const validatedPrev = sqliteSchema.parse(prev);
  const validatedCur = sqliteSchema.parse(cur);
  const squashedPrev = squashSqliteScheme(validatedPrev, "push");
  const squashedCur = squashSqliteScheme(validatedCur, "push");
  const { statements, _meta } = await applySqliteSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    tablesResolver,
    columnsResolver,
    sqliteViewsResolver,
    validatedPrev,
    validatedCur,
    "push"
  );
  const { shouldAskForApprove, statementsToExecute, infoToPrint } = await logSuggestionsAndReturn(
    db,
    statements,
    squashedPrev,
    squashedCur,
    _meta
  );
  return {
    hasDataLoss: shouldAskForApprove,
    warnings: infoToPrint,
    statementsToExecute,
    apply: async () => {
      for (const dStmnt of statementsToExecute) {
        await db.query(dStmnt);
      }
    }
  };
};
var generateMySQLDrizzleJson = async (imports, prevId, casing2) => {
  const { prepareFromExports: prepareFromExports5 } = await Promise.resolve().then(() => (init_mysqlImports(), mysqlImports_exports));
  const prepared = prepareFromExports5(imports);
  const id = randomUUID();
  const snapshot = generateMySqlSnapshot(prepared.tables, prepared.views, casing2);
  return {
    ...snapshot,
    id,
    prevId: prevId ?? originUUID
  };
};
var generateMySQLMigration = async (prev, cur) => {
  const { applyMysqlSnapshotsDiff: applyMysqlSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const validatedPrev = mysqlSchema.parse(prev);
  const validatedCur = mysqlSchema.parse(cur);
  const squashedPrev = squashMysqlScheme(validatedPrev);
  const squashedCur = squashMysqlScheme(validatedCur);
  const { sqlStatements } = await applyMysqlSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    tablesResolver,
    columnsResolver,
    mySqlViewsResolver,
    validatedPrev,
    validatedCur
  );
  return sqlStatements;
};
var pushMySQLSchema = async (imports, drizzleInstance, databaseName) => {
  const { applyMysqlSnapshotsDiff: applyMysqlSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const { logSuggestionsAndReturn: logSuggestionsAndReturn4 } = await Promise.resolve().then(() => (init_mysqlPushUtils(), mysqlPushUtils_exports));
  const { mysqlPushIntrospect: mysqlPushIntrospect2 } = await Promise.resolve().then(() => (init_mysqlIntrospect(), mysqlIntrospect_exports));
  const { sql: sql2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
  const db = {
    query: async (query, params) => {
      const res = await drizzleInstance.execute(sql2.raw(query));
      return res[0];
    }
  };
  const cur = await generateMySQLDrizzleJson(imports);
  const { schema: prev } = await mysqlPushIntrospect2(db, databaseName, []);
  const validatedPrev = mysqlSchema.parse(prev);
  const validatedCur = mysqlSchema.parse(cur);
  const squashedPrev = squashMysqlScheme(validatedPrev);
  const squashedCur = squashMysqlScheme(validatedCur);
  const { statements } = await applyMysqlSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    tablesResolver,
    columnsResolver,
    mySqlViewsResolver,
    validatedPrev,
    validatedCur,
    "push"
  );
  const { shouldAskForApprove, statementsToExecute, infoToPrint } = await logSuggestionsAndReturn4(
    db,
    statements,
    validatedCur
  );
  return {
    hasDataLoss: shouldAskForApprove,
    warnings: infoToPrint,
    statementsToExecute,
    apply: async () => {
      for (const dStmnt of statementsToExecute) {
        await db.query(dStmnt);
      }
    }
  };
};
var generateSingleStoreDrizzleJson = async (imports, prevId, casing2) => {
  const { prepareFromExports: prepareFromExports5 } = await Promise.resolve().then(() => (init_singlestoreImports(), singlestoreImports_exports));
  const prepared = prepareFromExports5(imports);
  const id = randomUUID();
  const snapshot = generateSingleStoreSnapshot(
    prepared.tables,
    /* prepared.views, */
    casing2
  );
  return {
    ...snapshot,
    id,
    prevId: prevId ?? originUUID
  };
};
var generateSingleStoreMigration = async (prev, cur) => {
  const { applySingleStoreSnapshotsDiff: applySingleStoreSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const validatedPrev = singlestoreSchema.parse(prev);
  const validatedCur = singlestoreSchema.parse(cur);
  const squashedPrev = squashSingleStoreScheme(validatedPrev);
  const squashedCur = squashSingleStoreScheme(validatedCur);
  const { sqlStatements } = await applySingleStoreSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    tablesResolver,
    columnsResolver,
    /* singleStoreViewsResolver, */
    validatedPrev,
    validatedCur,
    "push"
  );
  return sqlStatements;
};
var pushSingleStoreSchema = async (imports, drizzleInstance, databaseName) => {
  const { applySingleStoreSnapshotsDiff: applySingleStoreSnapshotsDiff2 } = await Promise.resolve().then(() => (init_snapshotsDiffer(), snapshotsDiffer_exports));
  const { logSuggestionsAndReturn: logSuggestionsAndReturn4 } = await Promise.resolve().then(() => (init_singlestorePushUtils(), singlestorePushUtils_exports));
  const { singlestorePushIntrospect: singlestorePushIntrospect2 } = await Promise.resolve().then(() => (init_singlestoreIntrospect(), singlestoreIntrospect_exports));
  const { sql: sql2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
  const db = {
    query: async (query) => {
      const res = await drizzleInstance.execute(sql2.raw(query));
      return res[0];
    }
  };
  const cur = await generateSingleStoreDrizzleJson(imports);
  const { schema: prev } = await singlestorePushIntrospect2(db, databaseName, []);
  const validatedPrev = singlestoreSchema.parse(prev);
  const validatedCur = singlestoreSchema.parse(cur);
  const squashedPrev = squashSingleStoreScheme(validatedPrev);
  const squashedCur = squashSingleStoreScheme(validatedCur);
  const { statements } = await applySingleStoreSnapshotsDiff2(
    squashedPrev,
    squashedCur,
    tablesResolver,
    columnsResolver,
    /* singleStoreViewsResolver, */
    validatedPrev,
    validatedCur,
    "push"
  );
  const { shouldAskForApprove, statementsToExecute, infoToPrint } = await logSuggestionsAndReturn4(
    db,
    statements,
    validatedCur,
    validatedPrev
  );
  return {
    hasDataLoss: shouldAskForApprove,
    warnings: infoToPrint,
    statementsToExecute,
    apply: async () => {
      for (const dStmnt of statementsToExecute) {
        await db.query(dStmnt);
      }
    }
  };
};
var upPgSnapshot = (snapshot) => {
  if (snapshot.version === "5") {
    return updateUpToV7(updateUpToV6(snapshot));
  }
  if (snapshot.version === "6") {
    return updateUpToV7(snapshot);
  }
  return snapshot;
};
export {
  generateDrizzleJson,
  generateMigration,
  generateMySQLDrizzleJson,
  generateMySQLMigration,
  generateSQLiteDrizzleJson,
  generateSQLiteMigration,
  generateSingleStoreDrizzleJson,
  generateSingleStoreMigration,
  pushMySQLSchema,
  pushSQLiteSchema,
  pushSchema,
  pushSingleStoreSchema,
  upPgSnapshot
};
