PostgreSQL 使用 search_path 进行多租户

PostgreSQL using search_path for multi tenancy

我正在开发一个使用 PostgreSQL 作为数据库的多租户 Web 应用程序,因为它支持一个数据库实例中的模式。但是我遇到了一个问题,为租户设置 search_path。

我正在使用 JavaEE 7 和 Wildfly 8.2.0。我创建了一个 MultiTenantConnectionProvider,它使用 DataSourceConnectionProvider 加载配置的 DataSource。

检索连接的方法将 search_path 设置为给定的 tenantId:

@Override
public Connection getConnection(String tenantId) throws SQLException
{
    Connection con = getAnyConnection();
    try
    {
        con.createStatement().execute("SET search_path = '" + tenantId + "'");
        LOG.info("Using " + tenantId + " as database schema");
    }
    catch (SQLException ex)
    {
        throw new HibernateException("Could not alter connection for specific schema");
    }
    return con;
}

对于第一次测试,我总是返回相同的 tenantId "customer1"。

我在 Postgres 上创建了一个用户,它有自己的数据库和一个模式 "customer1"。我有一个实体 user 定义如下:

@Entity
@Table(name = "user")
public class User implements Serializable
{
    @Id
    @GeneratedValue
    private Long id;
    @Column(unique = true, nullable = false)
    private String username;
    private String firstname;
    private String lastname;
    private String gender;
    @Column(unique = true, nullable = false)
    private String email;
    @Column(nullable = false)
    private byte[] password;
    private String passwordResetToken;
    @Column(nullable = false)
    private byte[] salt;
...
}

我在架构 "customer1" 中创建了 table。现在我的问题是 table 用户的 select 语句返回另一个用户 - table。我必须使用 table 显式设置架构名称,否则我查询错误的 table.

声明:

select * from user; -> current_user name: user1

returns:

| current_user name |
--------------------
| "skedflex"        |

声明:

select * from customer1.user;

returns:

| id | username | firstname | lastname | ... |
----------------------------------------------
| 1  | johnnie  | John      | Doe      | ... |

无法在查询中使用架构名称,因为该值是在运行时确定的,而我使用的是 JPA。因此无法在运行时查询执行期间插入架构名称。

我预计 search_path 足以查询数据。

我发现我的设置有问题。 在 PostgreSQL 中,user 是一个关键字,无法创建具有此名称的 tables,除非用户用引号转义:"user"。我已将 table 名称更改为 user_account,并且查询按预期工作。