首页 > 解决方案 > 在 Sequelize 中动态定义数据库以支持多租户返回错误的查询语法

问题描述

我正在使用共享数据库隔离架构原则开发多租户应用程序 (SAAS)。

我已经尝试过https://github.com/renatoargh/data-isolation-example的解决方案

从这篇文章https://renatoargh.wordpress.com/2018/01/10/logical-data-isolation-for-multi-tenant-architecture-using-node-express-and-sequelize/

这是使用模式选项的我的 Sequelize 模型

module.exports = (sequelize, DataTypes) => {
  const Task = sequelize.define('Task', {
    id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      field: 'Id'
    },

    description: {
      type: DataTypes.STRING(100),
      allowNull: false,
      field: 'Description'
    },

    done: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      default: false,
      field: 'Done'
    },

    taskTypeId: {
      type: DataTypes.INTEGER,
      allowNull: true,
      field: 'TaskTypeId'
    },

    userId: {
      type: DataTypes.INTEGER,
      allowNull: true,
      field: 'UserId'
    }
  }, {
      freezeTableName: true,
      tableName: 'Tasks',
      createdAt: false,
      updatedAt: false
    })
  Task.changeSchema = schema => Task.schema(schema)
  Task.associate = models => {
    Task.belongsTo(models.TaskType, {
      as: 'taskType',
      foreignKey: 'taskTypeId'
    })
  }


  return Task
}

并停在这个问题上

SELECT
  `Task`.`Id`              AS `id`,
  `Task`.`Description`     AS `description`,
  `Task`.`Done`            AS `done`,
  `Task`.`TaskTypeId`      AS `taskTypeId`,
  `Task`.`UserId`          AS `userId`,
  `taskType`.`Id`          AS `taskType.id`,
  `taskType`.`Description` AS `taskType.description`
FROM `tenant_1.Tasks` AS `Task` LEFT OUTER JOIN `shared.TaskTypes` AS `taskType`
    ON `Task`.`TaskTypeId` = `taskType`.`Id`
WHERE `Task`.`UserId` = 1;

如您所见, mysql 中的FROM `tenant_1.Tasks`是错误的语法。它必须来自`tenant_1`。`Tasks`

如何将`tenant_1.Tasks`更改为`tenant_1`.`Tasks`

标签: mysqlnode.jsmariadbsequelize.jsmulti-tenant

解决方案


你在使用 MySQL 吗?如果是这样,那是预期的行为。

Model.schema的文档中:

将模式应用于此模型。对于 postgres,这实际上会将架构放在表名前面 - "schema"."tableName",而架构将添加到 mysql 和 sqlite 的表名之前 - 'schema.tablename'


推荐阅读