Movatterモバイル変換


[0]ホーム

URL:



Facebook
Postgres Pro
Facebook
Downloads
42.6. A Database Login Event Trigger Example
Prev UpChapter 42. Event TriggersHome Next

42.6. A Database Login Event Trigger Example

The event trigger on thelogin event can be useful for logging user logins, for verifying the connection and assigning roles according to current circumstances, or for session data initialization. It is very important that any event trigger using thelogin event checks whether or not the database is in recovery before performing any writes. Writing to a standby server will make it inaccessible.

The following example demonstrates these options.

-- create test tables and rolesCREATE TABLE user_login_log (  "user" text,  "session_start" timestamp with time zone);CREATE ROLE day_worker;CREATE ROLE night_worker;-- the example trigger functionCREATE OR REPLACE FUNCTION init_session()  RETURNS event_trigger SECURITY DEFINER  LANGUAGE plpgsql AS$$DECLARE  hour integer = EXTRACT('hour' FROM current_time);  rec boolean;BEGIN-- 1. Forbid logging in during nighttimeIF hour BETWEEN 2 AND 4 THEN  RAISE EXCEPTION 'Login forbidden';END IF;-- The checks below cannot be performed on standby servers so-- ensure the database is not in recoverySELECT pg_is_in_recovery() INTO rec;IF rec THEN  RETURN;END IF-- 2. Assign some rolesIF hour BETWEEN 8 AND 20 THEN         -- at daytime grant the day_worker role  EXECUTE 'REVOKE night_worker FROM ' || quote_ident(session_user);  EXECUTE 'GRANT    day_worker TO '   || quote_ident(session_user);ELSE                                  -- at other time grant the night_worker role  EXECUTE 'REVOKE day_worker FROM ' || quote_ident(session_user);  EXECUTE 'GRANT  night_worker TO ' || quote_ident(session_user);END IF;-- 3. Initialize some user session dataCREATE TEMP TABLE session_storage (x float, y integer);-- 4. Log the connection timeINSERT INTO user_login_log VALUES (session_user, current_timestamp);END;$$;-- trigger definitionCREATE EVENT TRIGGER init_session  ON login  EXECUTE FUNCTION init_session();


Prev Up Next
42.5. A Table Rewrite Event Trigger Example Home Chapter 43. The Rule System
pdfepub
Go to Postgres Pro Enterprise 14
By continuing to browse this website, you agree to the use of cookies. Go toPrivacy Policy.

[8]ページ先頭

©2009-2025 Movatter.jp