gpt4 book ai didi

postgresql - 在 CakePHP 中使用特定命令在任何数据库访问之前

转载 作者:行者123 更新时间:2023-11-29 12:22:40 24 4
gpt4 key购买 nike

我是 CakePHP 的新手,使用的是 1.3 版。

如何在任何数据库操作之前动态更改 DATABASE_CONFIG 中的“模式”属性?我可以在任何数据库交互之前执行特定于 postgres 的命令“set search_path to 'schema_xyz'”的类是什么?

我想利用 Postgres 的能力在单个数据库中维护多个不同的命名空间(在 Postgres 的说法中也称为模式),以在我的应用程序中实现 Multi-Tenancy 。也就是说,每个命名空间都将包含相同的一组表,但显然内容不同。在这里,重要的是不要将模式理解为意思 table metadata ,而是作为 postgres-specific concept of namespace其中模式是表的容器。确切的 Postgres 命令并不重要。什么是它可以被调用的机制,并且避开了 Cake 表描述的典型含义,如 SchemaShell 中所见。我发现 Cake 暴露 namespace 概念的唯一地方是在 database.php 文件中,然后在首次建立数据库连接时使用该文件。参见:api13.cakephp.org/view_source/dbo-postgres/#line-113(新用户链接限制,抱歉)

    if ($this->connection) {
$this->connected = true;
$this->_execute("SET search_path TO " . $config['schema']);

我想在所有数据库查询之前设置 search_path,而不是像目前所做的那样仅在连接时设置。

作为概念证明,我尝试在我的模型中设置 $useDbConfig,但根据打印 SQL 命令的调试输出,这似乎只影响所有查询的一个子集。我已将其移至 app_model.php 中,结果相同。通过动态创建 db_config 实例并通过 loadDataSource 传递给 ConnectionManager 来增强它。也许我应该用各种风格的 before... 方法来编写代码。

我在网上看到很多帖子,人们讨论使用 database.php 中的几种数据库配置之一来为开发、实验室和生产环境使用不同的数据库。但是我有一个包含多个 namespace /模式的数据库。此外,我的此类 namespace 的数量太多且动态变化,无法在 database.php 中对新变量进行硬编码。

因此,在 CakePHP 的哪个位置我可以插入一些东西来在任何数据库命令之前设置 search_path?我稍后会处理优化。请记住,我是 Cake 的新手,所以请尽量具体。如果我可以澄清这个问题,请告诉我。

提前致谢。这是部分工作的代码片段:

class AppModel extends Model {
function beforeFind($queryData)
{
App::import("ConnectionManager");
$cm = &ConnectionManager::getInstance();

$namespace = 'xyz_namespace'; //name of the new schema/namespace/search path
$new_db_config_name = 'new_config'; //name for the new DB config to be used in the ConnectionManager
$new_db_config = $cm->config->default; //copy the 'default' DB config into an array
$new_db_config['schema'] = $namespace; //change/add the new schema/namespace/search path

$cm->create($new_db_config_name, $new_db_config); //turn the array into a DbConfig object
$cm->loadDataSource($new_db_config_name); //load the new DbConfig into the ConnectionManager
$this->useDbConfig = $new_db_config_name; //tell the model to new use the Db Config


return $queryData;
}
}

最佳答案

如果你想为每个登录角色切换模式,在 PostgreSQL 中有一个非常简单的方法:

ALTER ROLE foo SET search_path=bar, public;
ALTER ROLE baz SET search_path=bam, public;

因此,由该角色发起的连接会自动设置 search_path。
如果您的登录名与所需的模式名称相同,还有一种更简单的方法,我引用 the fine manual :

If one of the list items is the special value $user, then the schema having the name returned by SESSION_USER is substituted, if there is such a schema. (If not, $user is ignored.)

但请注意 - the fine manual再次:

Role-specific variable settings take effect only at login; SET ROLE and SET SESSION AUTHORIZATION do not process role-specific variable settings.

关于postgresql - 在 CakePHP 中使用特定命令在任何数据库访问之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7758746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com