在 postgresql 中使用模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11046152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 00:00:31  来源:igfitidea点击:

using schemas in postgresql

postgresqldatabase-schema

提问by Ottavio Campana

I have developed an application using postgresql and it works well.

我已经使用 postgresql 开发了一个应用程序,它运行良好。

Now I need to create several instances of the same application but I have only one database. So I am thinking about using schemas, so that I can group each instance tables in a different schema.

现在我需要创建同一个应用程序的多个实例,但我只有一个数据库。所以我正在考虑使用模式,以便我可以将每个实例表分组到不同的模式中。

Now, I wouldn't like to rewrite all my functions and script, thus I am wondering if I can just use some directive to instruct the database to operate on a specific schema. Just to try to make it clearer, do you know when in c++ you do

现在,我不想重写我所有的函数和脚本,因此我想知道是否可以使用一些指令来指示数据库对特定模式进行操作。只是为了让它更清楚,你知道在 C++ 中你什么时候做的吗?

using namespace std;

so that you can use coutinstead of std::cout? I would like to use someting similar if possible.

这样你就可以使用cout代替std::cout?如果可能的话,我想使用类似的东西。

回答by Richard Huxton

The parameter you are looking for is search_path- that lists the schemas a query will look in. So, you can do something like:

您正在寻找的参数是search_path- 列出查询将查看的模式。因此,您可以执行以下操作:

CREATE TABLE schema1.tt ...
CREATE TABLE schema2.tt ...
CREATE FUNCTION schema1.foo() ...
CREATE FUNCTION schema2.foo() ...
SET search_path = schema1, something_else;
SELECT * FROM tt;        -- schema1.tt
SELECT * FROM schema2.tt -- schema2.tt
SELECT foo();            -- calls schema1.foo
SELECT schema2.foo();    -- calls schema2.foo

Note that if a query's plan gets saved inside the body of foo() then you may get an unexpected results. I would recommend you always explicitly list schemas for referenced tables in plpgsql functions if you are using duplicated tables. If not, make sure you have testing in place to check behaviour with a chaning search_path.

请注意,如果查询的计划保存在 foo() 的主体中,那么您可能会得到意想不到的结果。如果您使用重复表,我建议您始终在 plpgsql 函数中明确列出引用表的模式。如果没有,请确保您进行了测试以检查使用 chaning search_path 的行为。

Oh - you can explicitly set search_path for a function's body too - see the manual's CREATE FUNCTION reference for details.

哦 - 您也可以为函数的主体显式设置 search_path - 有关详细信息,请参阅手册的 CREATE FUNCTION 参考。