如何在 hasura 中针对特定模式执行 graphql 查询?

How to execute graphql query for a specific schema in hasura?

如下截图可以看出,当前项目数据库(postgresql) named default 有这 4 个模式 - public、appcompany1、appcompany2 和 appcompany3。

他们共享一些公用表。现在,当我想为客户获取数据时,我会编写如下查询:

query getCustomerList {
    customer {
        customer_id
        ...
        ...
    }
}

它从 public 模式中获取所需的数据。

但根据要求,根据前端的用户交互,将为 appcompanyN(N=1,2,3,...,任意正整数)执行该查询。我如何实现这个目标?

注意:每当用户创建新公司时,都会为该公司创建一个新架构。所以schema总数不限于4.

我怀疑你看到的问题实际上并不存在。

一切都比看起来简单得多。

一个。所有那些 table 在哪里?

有很多模式内部具有相同(或几乎相同)的对象。

所有 table 都在 hasura 中注册。

Hasura 不能用相同的名字注册不同的 table,所以默认名字是 [schema_name]_[table_name](除了 public)

因此 table customer 将被注册为:

  • customer(来自public
  • appcompany1_customer
  • appcompany2_customer
  • appcompany3_customer

可以使用“自定义 GraphQL 根字段”在 GraphQL 架构中自定义实体名称。

乙。问题

But according to the requirements, depending on user interactions in front-end, that query will be executed for appcompanyN (N=1,2,3,..., any positive integer). How do I achieve this goal?

存在相同的对象,只是前缀与架构名称不同。

所以解决方案很简单

1。动态 GraphQL 查询

应用程序存储 GraphQL 查询模板,并在请求前用真实模式名称替换前缀。

例如

query getCustomerList{
   [schema]_customer{
   }
}

appcompany1appcompany2appcompanyZ替换[schema]并执行。

2。 SQL 查看所有数据

如果 table 100% 相同,则可以创建一个 sql 视图:

CREATE VIEW ALL_CUSTOMERS
AS
SELECT 'public' as schema,* FROM public.customer
UNION ALL 
SELECT 'appcompany1' as schema,* FROM appcompany1.customer
UNION ALL
SELECT 'appcompany2' as schema,* FROM appcompany2.customer
UNION ALL
....
SELECT `appcompanyZ',* FROM appcompanyZ.customer

这种方式:不需要动态查询,不需要注册所有模式中的所有对象。

您只需要注册视图与组合数据并使用一个查询

query{
query getCustomerList($schema: string) {
   all_customer(where: {schema: {_eq: $schema}}){
     customer_id
   }
}

关于这两种解决方案:很难称它们为优雅。

我自己都不喜欢他们两个;)

所以你自己决定哪个更适合你的情况table。