0

Clickhouse offical document implies one user can only have one profile, and database is configured in user section, readonly is configured in profile section, so, readonly will effect on all user's database. So, how can I set a user x which only can read database dbA, but can read and write database dbB?

mkdym
  • 101
  • 2
  • 6

1 Answers1

3

Consider using the SQL-driven access control management:

  1. Prepare test environment:
CREATE DATABASE db_01;
CREATE DATABASE db_02;
CREATE TABLE db_01.table_01 (id Int32) Engine = Memory();
CREATE TABLE db_02.table_02 (id Int32) Engine = Memory();
INSERT INTO db_01.table_01 VALUES (1), (2);
INSERT INTO db_02.table_02 VALUES (10), (20);
  1. Create user and assign the required privileges:
CREATE USER user_01 HOST ANY PROFILE 'default';

/* Set readonly access to DB 'db_01'. */
GRANT SELECT ON db_01.* TO user_01;

/* Set read-write access to DB 'db_02'. */
GRANT SELECT ON db_02.* TO user_01;
GRANT INSERT ON db_02.* TO user_01;
  1. Test (need to login as user_01):
SELECT currentUser(); /* Make sure that user is right. */
/*
┌─currentUser()─┐
│ user_01       │
└───────────────┘
*/

SHOW GRANTS; /* Double check the assigned privileges. */
/*
┌─GRANTS─────────────────────────────────────┐
│ GRANT SELECT ON db_01.* TO user_01         │
│ GRANT INSERT, SELECT ON db_02.* TO user_01 │
└────────────────────────────────────────────┘
*/

SELECT * FROM db_01.table_01; /* OK */
INSERT INTO db_01.table_01 VALUES (3); /* DB::Exception: user_01: Not enough privileges. */

SELECT * FROM db_02.table_02; /* OK */
INSERT INTO db_02.table_02 VALUES (30); /* OK */

The code above is just for the demo, you need to consider introduce roles/quotas/.., inherit another user-profile (more restrictive, not 'default') etc.

vladimir
  • 13,428
  • 2
  • 44
  • 70
  • This new functionality seems to be released with new version(20.x), but we are using 18.16 in production. Is there other way to do this? If no, I will consider upgrade version. – mkdym May 14 '20 at 05:47
  • Unfortunately no other way. Maybe make sense to create two separate users - one as writable, second - readonly? (fyi: there is section [allow_databases](https://stackoverflow.com/a/43265589/303298) that can be useful too) – vladimir May 14 '20 at 13:28
  • Thanks a lot. But I need query several databases in one session, so I have to use the same user. I will consider other solutions or update ck. – mkdym May 16 '20 at 09:51
  • Direct create user is throw error on version 21.12.2.7 . Change it into : CREATE USER user_01 HOST ANY SETTINGS PROFILE 'default'; – dalei19 Dec 21 '21 at 06:38