简体   繁体   English

多租户-是预先创建表格还是根据需要创建表格?

[英]Multi-tenancy - Create tables up-front or as needed?

I'm currently working on a SaaS type application, and for multi-tenancy I've settled on one database per user, with each database containing all tables required by the functionality the user is entitled to (have payed for). 我目前正在开发一个SaaS类型的应用程序,对于多租户,我已经为每个用户建立了一个数据库,每个数据库都包含用户有权使用(已付费)功能所需的所有表。 The application is designed to capture data (ie like web analytics) and present it for the user. 该应用程序旨在捕获数据(例如,类似于Web分析)并将其呈现给用户。 The design should be able to scale to the tens of thousands of users (eventually). 该设计应该能够扩展到成千上万的用户(最终)。

Would a viable solution be to create the tables 'dynamically' when the application detects they are required? 当应用程序检测到需要表时,可行的解决方案是“动态”创建表吗? Or should I create all eventually required tables in specific user databases, as soon as I know they may be needed (user upgrade, new features, etc.)? 还是我一知道可能需要在用户数据库中创建所有最终需要的表(用户升级,新功能等)?

My current architecture would allow me to do something like this: 我当前的体系结构将允许我执行以下操作:

function insertData($table, $data) {
    mysql_query("INSERT INTO ".$table." VALUES ('".implode("', '", $data)."')");
    if ( mysql_errno() ) {
      if (mysql_errno() == 1146) { // table does not exist
        if ( $this->createTable($table) ) {
          $this->insertData($table, $data)
        }
      } else {
        // other errors
      }
    }
}

I would like the flexibility to be able to add functionality without having to loop through all user databases to add tables, so a setup like the above would help me achive that. 我希望能够灵活地添加功能而不必遍历所有用户数据库来添加表,因此像上面的设置将帮助我实现这一点。 But I'm not sure if I'm missing something that would make me regret the decision later? 但是我不确定是否遗漏了会让我后悔这一决定的东西?

Using an insert to test whether a table exists may not be your best bet, particularly considering the size of the row and latency to the database server. 使用插入来测试表是否存在可能不是您的最佳选择,尤其是考虑到行的大小和数据库服务器的延迟。 A better solution might be to use 'show tables', ie: 更好的解决方案可能是使用“显示表​​”,即:

SHOW TABLES LIKE 'TABLENAME';

The resultset will be something like this: 结果集将如下所示:

Tables_in_DATABASENAME (TABLENAME)
----------------------------------
be_groups

If the number of rows is zero, clearly the table does not exist. 如果行数为零,则显然该表不存在。

As far as your process is concerned -- I think I'd take a hybrid approach. 就您的流程而言,我想我会采用混合方法。 When the customer upgrades and as part of your provisioning workflow create all the tables needed to provide the new services to the customer. 当客户升级时,作为您的供应工作流程的一部分,请创建为客户提供新服务所需的所有表。 That way the customer doesn't take up any more resources (disk mainly, in this case) than they're paying for, and you're not causing yourself the pain of provisioning dynamically. 这样一来,客户所占用的资源(在这种情况下主要是磁盘)就不会花费比他们所支付的更多的资源,并且不会给自己带来动态配置的麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM