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 1oKpkN-0002u4-Q6 for pgsql-sql@arkaria.postgresql.org; Sun, 07 Aug 2022 23:31:51 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1oKpkL-0003gS-1f for pgsql-sql@arkaria.postgresql.org; Sun, 07 Aug 2022 23:31:49 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1oKpkK-0003dO-NI for pgsql-sql@lists.postgresql.org; Sun, 07 Aug 2022 23:31:48 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1oKpkF-0002co-8m for pgsql-sql@lists.postgresql.org; Sun, 07 Aug 2022 23:31:44 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.15.2/8.15.2) with ESMTP id 277NVfiS291123; Sun, 7 Aug 2022 19:31:41 -0400 From: Tom Lane To: Adam Mackler cc: "pgsql-sql@lists.postgresql.org" Subject: Re: Possible bug (or at least unexpected behavior) In-reply-to: References: Comments: In-reply-to Adam Mackler message dated "Sun, 07 Aug 2022 20:06:21 -0000" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <291121.1659915101.1@sss.pgh.pa.us> Content-Transfer-Encoding: quoted-printable Date: Sun, 07 Aug 2022 19:31:41 -0400 Message-ID: <291122.1659915101@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Adam Mackler writes: > Briefly, given the following function: > CREATE FUNCTION runs(input int[], output int[] DEFAULT '{}') > RETURNS int[] AS $$ > SELECT > CASE WHEN cardinality(input) =3D 0 THEN output > ELSE runs(input[2:], > array_append(output, CASE > WHEN input[1] =3D 0 THEN 0 > ELSE output[cardinality(output)] + input[1] > END) > ) > END > $$ LANGUAGE SQL; > I expect the following invocation to return an array with the same numbe= r of elements as the passed-in argument array: > # select runs('{0,1,1,1,1,0,-1,-1,-1,0}'); > runs > ---------------------------------------- > {0,1,2,3,4,5,6,0,0,0,-1,-2,-3,-4,-5,0} > (1 row) Yeah, there's a bug in here somewhere. If you transpose the logic into plpgsql, it behaves fine: CREATE FUNCTION runs_p(input int[], output int[] DEFAULT '{}') RETURNS int[] AS $$ begin return CASE WHEN cardinality(input) =3D 0 THEN output ELSE runs_p(input[2:], array_append(output, CASE WHEN input[1] =3D 0 THEN 0 ELSE output[cardinality(output)] + input[1] END) ) END; end $$ LANGUAGE plpgsql; so that might do as a workaround. It looks like memory management in SQL functions is not coping well with expanded arrays, but I'm not quite sure where it's going off the rails. regards, tom lane