简体   繁体   English

在视图中动态选择架构名称

[英]Dynamically choosing a schema name in a view

I have a view for multiple tables with the same structure but in different schemas: 我有一个具有相同结构但模式不同的多个表的视图:

create table a.persons (
    name text primary key
);
create table b.persons (
    name text primary key
);
create view dynamic_persons as select * from SCHEMA.persons;

I want to be a able to get SCHMEA dynamically from a function or jwt attribute ( current_setting('jwt.claims.schema') for example). 我希望能够从函数或jwt属性(例如current_setting('jwt.claims.schema')动态获取SCHMEA
Is it possible to do? 有可能吗?

您应该set schemaset search_path to或者select set_config来更改架构,但是视图定义已保存,因此要动态运行它,您将不得不在每次运行时重新创建视图,这没有任何意义。

You can use a table function for that. 您可以为此使用表函数。 Create a function, that takes an argument and depending on that argument either queries a.persons or b.persons . 创建一个函数,该函数接受一个参数,并根据该参数查询a.personsb.persons

Example: 例:

CREATE TYPE schema_switch AS ENUM ('a', 'b');

CREATE OR REPLACE FUNCTION dynamic_view (_schema schema_switch)
RETURNS TABLE (name text)
AS
$$
DECLARE
  x INT;
BEGIN
  CASE 
    WHEN _schema ='a'
      THEN RETURN QUERY SELECT persons.name
                               FROM a.persons;
    WHEN _schema ='b'
      THEN RETURN QUERY SELECT persons.name
                               FROM b.persons;
  END CASE;
END;
$$
LANGUAGE plpgsql;

Called like dynamic_view('a') would return the records from a.persons , dynamic_view('b') those from b.persons . 所谓的像dynamic_view('a')将从返回记录a.personsdynamic_view('b')来自b.persons

In the example I created a new enum type here only allowing 'a' or 'b' for input. 在示例中,我在此处创建了一个新的枚举类型,仅允许输入'a''b' That makes it less error prone. 这样可以减少出错的可能性。 But you could of course also do it with a varchar and RAISE an error, if an invalid value was passed. 但是,你当然也可以用做varcharRAISE错误,如果无效值传递。 You could also use dynamic SQL to allow passing an arbitrary schema name using RETURN QUERY EXECUTE . 您还可以使用动态SQL允许使用RETURN QUERY EXECUTE传递任意模式名称。 But be sure to check the input for sanity then.Like look up pg_catalog.pg_namespace if such a schema exists. 但是一定要检查输入是否合理,例如如果存在这样的模式,请查找pg_catalog.pg_namespace

Maybe there is also a possibility doing it with rules instead of a function. 也许还有可能​​使用规则而不是功能来实现。

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

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