Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1nn7YY-0001M3-IU for pgsql-general@arkaria.postgresql.org; Fri, 06 May 2022 23:40:18 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1nn7YV-0004cj-Dw for pgsql-general@arkaria.postgresql.org; Fri, 06 May 2022 23:40:15 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1nn7YV-0004ca-0P for pgsql-general@lists.postgresql.org; Fri, 06 May 2022 23:40:15 +0000 Received: from mail-pl1-x631.google.com ([2607:f8b0:4864:20::631]) by magus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.92) (envelope-from ) id 1nn7YQ-0007ri-OJ for pgsql-general@lists.postgresql.org; Fri, 06 May 2022 23:40:14 +0000 Received: by mail-pl1-x631.google.com with SMTP id n8so8876902plh.1 for ; Fri, 06 May 2022 16:40:10 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=yugabyte.com; s=google; h=from:mime-version:subject:message-id:date:to; bh=lQ+Xyn8KXAuIxgPL+73XjospbEBQMvxaw+GgBfCBcK0=; b=LU7nTuvvlAdqcf189Tvxv+BT4pemgXLETuqNfm4wIgnsONrCtRV4lsTImXbaHcgPxL xcJcn7PI7oEjW9k5Dkl3QSXyEDycEAF3+417i9wX1qlfxOqjFJewuRxghKGfS6xM2PFU IjB7GNhwrppQEkc5JisdbDRNDfM9V2hfLNeGQ= X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=x-gm-message-state:from:mime-version:subject:message-id:date:to; bh=lQ+Xyn8KXAuIxgPL+73XjospbEBQMvxaw+GgBfCBcK0=; b=OwzbYk9EmsdinKHz6j7OhVmhZlFa/06Ahy5lmmLzz3XI1TQ+Ef9ESV3vaglqHcICfT QqNvPmQvUjUUfFbl+aW2QgFd78d2a11sPvUjKMFxpy9aksctXEaFWfHI/xcJ81nkWU/D /4Dc+N3K1IldpCgydpioxRZNbi2/hsFf37894p27SzyomXHXjZ7JIV6/ts1WDjeJ2ROU zaAj7r/h2D35jhM3B7YI3+F9/TdA9Gtl4a5VwUl95+U8a9iqqeVzX4lRuR4+I91docea PQ6BP2nOZQ06Nc7uWeMmkXL9a2l8Uh2MqGUTuM6EdgpU2APYPPU5r3IqHTj3A7cHCiR+ fc8Q== X-Gm-Message-State: AOAM530kW5UTaAW0GN3AInjEQI+Dzok+My12lrjebLoCHLFohS6Lsh9C QDJ5QS5NggdR/4tbZ7PEyL/u2n+aaJoM+Q== X-Google-Smtp-Source: ABdhPJz4VEVmWA7n2vjjiudT5jSdxWdetyecMpyeoLxfdQNq2Xqu8qbHuGK7WNNCdAvScaibeJ9svA== X-Received: by 2002:a17:902:854c:b0:159:a70:deca with SMTP id d12-20020a170902854c00b001590a70decamr6137623plo.142.1651880407208; Fri, 06 May 2022 16:40:07 -0700 (PDT) Received: from smtpclient.apple ([2601:646:101:7fda:a90f:1be4:88a2:85c4]) by smtp.gmail.com with ESMTPSA id r13-20020a17090aa08d00b001cd4989fee4sm7888938pjp.48.2022.05.06.16.40.04 for (version=TLS1_2 cipher=ECDHE-ECDSA-AES128-GCM-SHA256 bits=128/128); Fri, 06 May 2022 16:40:05 -0700 (PDT) From: Bryn Llewellyn Content-Type: multipart/alternative; boundary="Apple-Mail=_020144EC-6E09-4E4F-8165-220A4A650FF0" Mime-Version: 1.0 (Mac OS X Mail 14.0 \(3654.120.0.1.13\)) Subject: "A transaction cannot be ended inside a block with exception handlers." Message-Id: <40EB34E2-F9CA-4D29-B0BE-6DF3D4D0FBA3@yugabyte.com> Date: Fri, 6 May 2022 16:40:03 -0700 To: pgsql-general list X-Mailer: Apple Mail (2.3654.120.0.1.13) List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk --Apple-Mail=_020144EC-6E09-4E4F-8165-220A4A650FF0 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset=utf-8 The PG doc section 43.8. Transaction Management: https://www.postgresql.org/docs/current/plpgsql-transactions.html says "A transaction cannot be ended inside a block with exception = handlers." It's easy to demonstrate the restriction by adding this just = before the final "end;" in the simple example at the start of the = section: exception when invalid_transaction_termination then raise info 'invalid_transaction_termination caught'; The procedure now terminates with "invalid_transaction_termination = caught". The "Transaction Management" section is new, in the "PL/pgSQL - SQL = Procedural Language" chapter, in Version 11. The caveat is there. And = it's been there ever since. I'd been hoping that the restriction would = have been lifted by version 14. I want to demonstrate how to meet this requirement: =C2=AB Encapsulate each business function in a user-defined subprogram that = hides all the implementation details like table names and the SQL = statements that manipulate their contents so the they cannot be seen = using SQL issued from the client. Further, don't allow raw errors to = escape to the client. Rather, if an expected error occurs (like a unique = key violation), then report this as an application-specific code that = translates to, for example, "This nickname is already taken. Choose a = different one." And if an "others" error occurs (typically because the = programmer forgot to cater for it=E2=80=94like a too-wide varchar value) = insert diagnostic info into an incident log table and return an = "unexpected error" application-specific code together with the incident = ID so that it can be reported to Support. =C2=BB I've written proof-of-concept code that shows how to meet this = requirement for most scenarios. But it seems to be impossible to meet = the requirement for errors that occur at commit time. Such errors occur, = for example, when two "serializable" sessions contend. It's easy to = provoke a commit-time error in a single session demo with an "initially = deferred" constraint trigger. (See the code at the end.) Another example = would be an "initially deferred" FK constraint where an application code = bug occasionally fails to meet the required conditions before the = commit. Is there simply no way that inserts into table "t" in my example can be = encapsulated in PL/pgSQL so that the error from the failing trigger can = be handled rather there than escaping, raw, to the client? ------------------------------------------------------------ -- "initially deferred" constraint trigger demo create table t(k int primary key); create function trg_fn() returns trigger language plpgsql as $body$ declare bad constant boolean not null :=3D (select exists(select 1 from t where k =3D 42)); begin -- Uncomment to observe when trg fires. -- raise info 'trg fired'; if bad then assert 'false', 'tigger trg caused exception'; end if; return null; end; $body$; create constraint trigger trg after insert on t initially deferred for each row execute function trg_fn(); ------------------------------------------------------------ -- Do by hand, statement by statement. -- OK -- Notice that "trg" fire, five times, at "commit" time. start transaction; insert into t(k) values(1), (2), (3), (4), (5); commit; -- "ERROR: tigger trg caused exception" occurs at "commit" time. start transaction; insert into t(k) values(42); commit; ------------------------------------------------------------ --Apple-Mail=_020144EC-6E09-4E4F-8165-220A4A650FF0 Content-Transfer-Encoding: quoted-printable Content-Type: text/html; charset=utf-8
The PG doc = section 43.8. Transaction Management:

says "A transaction cannot be ended inside a block with = exception handlers." It's easy to demonstrate the restriction by adding = this just before the final "end;" in the simple example at the = start of the section:

exception
  when = invalid_transaction_termination then
  =   raise info 'invalid_transaction_termination caught';

The = procedure now terminates with "invalid_transaction_termination = caught".

The = "Transaction Management" section is new, in the = "PL/pgSQL - SQL Procedural Language" chapter, in Version = 11. The caveat is there. And it's been there ever since. I'd been hoping = that the restriction would have been lifted by version 14.

I want to demonstrate = how to meet this requirement:

=C2=AB
Encapsulate = each business function in a user-defined subprogram that hides all the = implementation details like table names and the SQL statements that = manipulate their contents so the they cannot be seen using SQL issued = from the client. Further, don't allow raw errors to escape to the = client. Rather, if an expected error occurs (like a unique key = violation), then report this as an application-specific code that = translates to, for example, "This nickname is already taken. Choose a = different one." And if an "others" error occurs (typically because the = programmer forgot to cater for it=E2=80=94like a too-wide varchar value) = insert diagnostic info into an incident log table and return an = "unexpected error" application-specific code together with the incident = ID so that it can be reported to Support.
=C2=BB

I've written proof-of-concept code that shows how to meet = this requirement for most scenarios. But it seems to be impossible to = meet the requirement for errors that occur at commit time. Such errors = occur, for example, when two "serializable" sessions contend. It's easy = to provoke a commit-time error in a single session demo with an = "initially deferred" constraint trigger. (See the code at the end.) = Another example would be an "initially deferred" FK constraint where an = application code bug occasionally fails to meet the required conditions = before the commit.

Is there simply no way that inserts into table "t" in my = example can be encapsulated in PL/pgSQL so that the error from the = failing trigger can be handled rather there than escaping, raw, to the = client?

------------------------------------------------------------
-- "initially deferred" constraint trigger = demo

create table t(k int primary = key);

create function = trg_fn()
  returns = trigger
  language = plpgsql
as $body$
declare
  bad = constant boolean not null :=3D
  =   (select exists(select 1 from t where k =3D 42));
begin
  -- Uncomment to observe when trg fires.
  -- raise info 'trg fired';
  if bad then
  =   assert 'false', 'tigger trg caused exception';
  end if;
  return null;
end;
$body$;

create constraint trigger = trg
after insert on t
initially deferred

for each = row
execute function trg_fn();

------------------------------------------------------------
-- = Do by hand, statement by statement.

-- OK
-- Notice that "trg" fire, five times, at = "commit" time.
start transaction;
insert = into t(k) values(1), (2), (3), (4), (5);
commit;

-- "ERROR: tigger trg caused exception" occurs = at "commit" time.
start transaction;
insert = into t(k) values(42);
commit;

------------------------------------------------------------

= --Apple-Mail=_020144EC-6E09-4E4F-8165-220A4A650FF0--