Postgres: วิธี grant permission สำหรับ Database, schemas, tables และ sequences

ก่อนอื่นต้องเป็น user ที่มีสิทธิ์เช้าถึง database และ schema โดยการรัน SQL นี้

SELECT nspname FROM pg_catalog.pg_namespace;

คำสั่งสำหรับ grant database

GRANT ALL PRIVILEGES ON DATABASE yourDBName to yourDBUser;

ALL PRIVILEGES หมายถึง SELECTINSERTUPDATEDELETETRUNCATEREFERENCESTRIGGERCREATECONNECTTEMPORARYEXECUTE, และ USAGE

การจะ Grant table ได้ ต้องระบุ schema ที่ table นั้นๆ อยู่
คำสั่งสำหรับ grant table ในแต่ละ schema

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA schemaName TO yourDBUser

แล้วหากเรามีหลาย schema ล่ะ ทำไงดี execute ทีล่ะ schema ก็เป็นวิธีหนึ่ง แต่จะง่ายกว่าถ้าเรา loop เพื่อ execute ทีละ schema ซึ่ง postgres สามารถทำได้เลยผ่าน function

DO $do$
DECLARE
    sch text;
BEGIN
    FOR sch IN SELECT schema_name FROM information_schema.schemata
    LOOP
        EXECUTE format($$ GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA %I TO yourDBUser $$, sch);
    END LOOP;
END;
$do$;

References

https://www.postgresql.org/docs/current/ddl-priv.html

Advertisement

ใส่ความเห็น

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  เปลี่ยนแปลง )

Twitter picture

You are commenting using your Twitter account. Log Out /  เปลี่ยนแปลง )

Facebook photo

You are commenting using your Facebook account. Log Out /  เปลี่ยนแปลง )

Connecting to %s