Skip to main content
The condition of a row policy can read a custom setting with the getSetting function. A single policy then filters the table by a value that is supplied with each query, set for a session, or fixed for a user, for example a tenant ID.

Example

As an administrator, create a table, a role that can read it, a user, and the policy:
Connected as app_user, pass the setting with the query:
Or set it once for the session:
Over the HTTP interface, pass the setting as a URL parameter:

Missing and unexpected values

A value that matches no tenant returns no rows. If the setting is not set at all, the query fails:
To return an empty result instead of an error, use getSettingOrDefault in the policy:
A custom setting keeps the type of the value you assign. Give it the type of the column it is compared with: with the String column of this example, SETTINGS SQL_tenant_id = 42 fails with a NO_COMMON_TYPE error.

The prefix of custom settings

The name of a custom setting must start with one of the prefixes listed in the custom_settings_prefixes server setting. The config.xml file that ships with ClickHouse sets it to SQL_, and in ClickHouse Cloud the prefix is always SQL_. On a server without this prefix, SET SQL_tenant_id = 'tenant_a' fails with Unknown setting 'SQL_tenant_id'.

Who is allowed to set the value

A user who can run their own SQL can set SQL_tenant_id to any value and read the rows of any tenant. The policy protects the data only if the end user cannot choose the value.
There are two ways to make sure of that:
  • Let a trusted application set the value. The application connects as app_user, adds the tenant of the authenticated end user to every request, and never passes SQL or settings from the end user through.
  • Fix the value for a database user with a CONST constraint:
    This user sees the rows of tenant_a without passing the setting, and an attempt to change it is refused:
The policy applies to sessions in which the tenant_reader role is enabled. With the default server configuration, a user who has SELECT on the table and to whom no policy applies sees all rows. Grant SELECT on the table only through the role that the policy names, or add policies for the other users. See the TO clause of CREATE ROW POLICY.