
  fHandle  UTL_FILE.FILE_TYPE;
  logLine  TEXT;
  caller   TEXT;
  result   accessHistoryRow;
  isSuper  BOOLEAN;
  userName TEXT;
  paramVal TEXT;
BEGIN
  userName := targetRole;
  SELECT pg_catalog.SESSION_USER INTO caller;
  IF (targetRole IS NULL) THEN
    userName := caller;
  ELSIF (targetRole != caller) THEN
    SELECT usesuper INTO isSuper FROM pg_catalog.pg_user WHERE usename = caller;
	IF (NOT isSuper) THEN
	  RAISE 'Must be a superuser to query access history for other users';
	END IF;
  END IF;
  -- Validate log_line_prefix
  SELECT setting INTO paramVal FROM pg_catalog.pg_settings WHERE name = 'log_line_prefix';
  IF (substring(paramVal, 1, 7) != '%t, %u:') THEN
      RAISE 'log_line_prefix is misconfigured - must be set to "%%t, %%u:"';
  END IF;
  -- Validate log_connections
  SELECT setting INTO paramVal FROM pg_catalog.pg_settings WHERE name = 'log_connections';
  IF( paramVal != 'on') THEN
      RAISE 'log_connections is misconfigured - must be set to "on"';
  END IF;
  -- Open the log file
  fHandle := UTL_FILE.fopen(directory, logFileName, 'r');
  -- Read all entries in the log file, searching for 
  -- connect entries for the specified role
  LOOP
     UTL_FILE.GET_LINE(fHandle, logLine);
     IF (logLine ~ '^.*, .*:LOG:[ ]*connection authorized:') THEN
       IF (logLine ~ ( 'user=' || userName)) THEN
	     result.roleName = userName;
		 result.connectTime = trim(trailing ',' FROM substring(logLine FROM '^.*,'));
		 result.success = TRUE;
		 RETURN NEXT result;
       END IF;
	 ELSIF (logLine ~ '^.*, .*:FATAL:[ ]*password authentication failed for user.*') THEN
       IF (logLine ~ ( 'user "' || userName || '"')) THEN
	     result.roleName = userName;
		 result.connectTime = trim(trailing ',' FROM substring(logLine FROM '^.*,'));
		 result.success = FALSE;
		 RETURN NEXT result;
       END IF;
     END IF;
  END LOOP;
  EXCEPTION 
    WHEN NO_DATA_FOUND THEN
	  UTL_FILE.FCLOSE(fHandle);
END