/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var mysql_to_mysql_exports = {};
__export(mysql_to_mysql_exports, {
  MySQLToMySQLBridge: () => MySQLToMySQLBridge
});
module.exports = __toCommonJS(mysql_to_mysql_exports);
var import_node_sql_parser = require("node-sql-parser");
var import_remote_local_bridge = require("./remote-local-bridge");
var import_lodash = __toESM(require("lodash"));
class MySQLToMySQLBridge extends import_remote_local_bridge.RemoteLocalBridge {
  async createServer(options) {
    const { transaction } = options;
    const servers = await this.localDatabase.sequelize.query(
      "SELECT * FROM mysql.servers WHERE `Server_name` = :serverName",
      {
        replacements: { serverName: options.serverName },
        transaction,
        type: "SELECT"
      }
    );
    if (servers.length) {
      return;
    }
    await this.localDatabase.sequelize.query(
      `
        CREATE SERVER '${options.serverName}'
FOREIGN DATA WRAPPER mysql
OPTIONS (USER :user, HOST :host, PORT ${options.port}, DATABASE :database, PASSWORD :password);
        `,
      {
        replacements: { ...options },
        transaction
      }
    );
  }
  async createTable(options) {
    const { remoteTableInfo, transaction, localModel, remoteServerName } = options;
    await this.localDatabase.sequelize.query(`DROP TABLE IF EXISTS ${localModel.tableName}`, {
      transaction
    });
    let { remoteTableDefinition } = options;
    if (remoteTableDefinition) {
      remoteTableDefinition = this.replaceTableName(remoteTableDefinition, localModel.tableName);
    }
    const parser = new import_node_sql_parser.Parser();
    const ast = parser.astify(remoteTableDefinition, {
      database: "MySQL"
    });
    ast.table_options = [
      { keyword: "engine", symbol: "=", value: "FEDERATED" },
      {
        keyword: "default charset",
        symbol: "=",
        value: (() => {
          const existCharset = ast.table_options.find((tableOpt) => tableOpt.keyword === "default charset");
          if (existCharset) {
            return existCharset.value;
          }
          return "utf8mb4";
        })()
      },
      {
        keyword: "connection",
        symbol: "=",
        value: `'${remoteServerName}/${remoteTableInfo.tableName}'`
      }
    ];
    ast.create_definitions = ast.create_definitions.map((def) => {
      return import_lodash.default.omit(def, ["collate", "character_set"]);
    });
    const sql = parser.sqlify(ast, {
      database: "MySQL"
    });
    await this.localDatabase.sequelize.query(sql, {
      transaction
    });
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  MySQLToMySQLBridge
});
