Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1XodSt-0000I7-HL for pgsql-jdbc@arkaria.postgresql.org; Wed, 12 Nov 2014 19:20:27 +0000 Received: from localhost ([127.0.0.1] helo=postgresql.org) by malur.postgresql.org with smtp (Exim 4.80) (envelope-from ) id 1XodSt-0005gq-25 for pgsql-jdbc@arkaria.postgresql.org; Wed, 12 Nov 2014 19:20:27 +0000 Received: from makus.postgresql.org ([2001:4800:1501:1::229]) by malur.postgresql.org with esmtps (TLS1.2:DHE_RSA_AES_256_CBC_SHA256:256) (Exim 4.80) (envelope-from ) id 1XodSs-0005gk-D3 for pgsql-jdbc@postgresql.org; Wed, 12 Nov 2014 19:20:26 +0000 Received: from mail-wg0-x22a.google.com ([2a00:1450:400c:c00::22a]) by makus.postgresql.org with esmtps (TLS1.0:RSA_AES_256_CBC_SHA1:256) (Exim 4.80) (envelope-from ) id 1XodSo-0005vO-1j for pgsql-jdbc@postgresql.org; Wed, 12 Nov 2014 19:20:24 +0000 Received: by mail-wg0-f42.google.com with SMTP id k14so14985443wgh.15 for ; Wed, 12 Nov 2014 11:20:20 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20120113; h=content-type:mime-version:subject:from:in-reply-to:date:cc :content-transfer-encoding:message-id:references:to; bh=XAL/QL0M7t+WVI+EZlr6rXErB3c1e8mVgdpuYcfIrHM=; b=vjEIjI0GRP3Vv/rud4eBtH3XAfmFmABWRz5VVG42e7hfrHXzh6Y0wEPXH1A27mR7oz mF/zxwqg8M/TZln5zeUGfGn6JyazbS0HPmqkde/VsFjxZ+p8CF++B+UB+hzP/BB1g0ld 5xD7s3q4ei3td+VZE9rfczIm39pzPrtGs2gUBjKGsXOxolyqFOcqNs4o0E+oaqWylri7 Sg1dRAFdlMAm7+9Gtfsbb3gOc75a1ezIlNKcB3d+FMF7IAxPHEkG5e8JbyfR+o0T3Nm7 eHEgrde/cHVtM28ji1gLn2DDLxhUGl+nZzYXp6Z0pWiFyKwTiR0SEJ9461ydOYKnB4W9 gPbA== X-Received: by 10.194.19.4 with SMTP id a4mr65574330wje.3.1415820020447; Wed, 12 Nov 2014 11:20:20 -0800 (PST) Received: from [192.168.1.101] (cpe-188-129-64-189.dynamic.amis.hr. [188.129.64.189]) by mx.google.com with ESMTPSA id i3sm22776622wix.0.2014.11.12.11.20.19 for (version=TLSv1 cipher=ECDHE-RSA-RC4-SHA bits=128/128); Wed, 12 Nov 2014 11:20:19 -0800 (PST) Content-Type: text/plain; charset=iso-8859-1 Mime-Version: 1.0 (Mac OS X Mail 7.3 \(1878.6\)) Subject: Re: New significance of holdable result sets in Java 8 From: Marko Topolnik In-Reply-To: <75C17D7A-95D9-471F-AF64-EFE83D971654@gmail.com> Date: Wed, 12 Nov 2014 20:20:13 +0100 Cc: "pgsql-jdbc@postgresql.org JDBC" , Brian McCallister Content-Transfer-Encoding: quoted-printable Message-Id: <5855156D-8010-4735-A63D-DC5DF5EABD27@gmail.com> References: <771672CB-9567-4966-8CE9-9D84E4F858D8@gmail.com> <75C17D7A-95D9-471F-AF64-EFE83D971654@gmail.com> To: Steven Schlansker X-Mailer: Apple Mail (2.1878.6) X-Pg-Spam-Score: -2.7 (--) List-Archive: List-Help: List-ID: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: X-Mailing-List: pgsql-jdbc Precedence: bulk Sender: pgsql-jdbc-owner@postgresql.org On 12. stu. 2014., at 19:45, Steven Schlansker = wrote: > Thanks for bringing this up! I'm not an expert on the PG FE/BE protocol,= so please excuse my ignorance below :) >=20 > On Nov 12, 2014, at 7:22 AM, Marko Topolnik wr= ote: >>=20 >> Data is passed from Controller to View as the return value of a method. = Traditionally, if you wanted a collection-shaped response, you would return= a List. This meant eager loading of all data needed for the response, whic= h caused scalability issues related to the JVM heap space. >=20 > We solved this problem (pre-Streams) by inverting the flow of control. I= n pseudo-JAX-RS with Jackson: >=20 > @Path("/objects") > public StreamingOutput getObjects() { > return os -> { > JsonGenerator jg =3D new JsonGenerator(os); > ResultSet rs =3D findObjects(); // make sure to do this in a txn with = fetch size set sensibly or you will collect all rows eagerly > while (rs.hasNext()) { jg.writeObject(rs.getString("whatever")); } > jg.close(); rs.close(); > }; > } I am aware of this approach; I even discuss it as a typical workaround in m= y blog post [1]. The problem is, this completely dispenses with the detaile= d and complex setup present in the View layer: the response format can be d= riven by the Accept HTTP header, encoding may be adapted to the request, an= d so on. I did pretty much that in my Clojure projects because Clojure's ec= osystem isn't as well-developed so roll-your-own solutions are the norm. Wi= th Spring, however, you lose a great deal when you give your Controller met= hod access to the raw response. I have already developed a Stream-based REST service along the lines I disc= uss in the mentioned blog post and the advantages are quite clear to me. It= is a direction that Spring would probably like to move in as well. [1] http://www.airpair.com/v1/posts/spring-streams-memory-efficiency >=20 >> With the Streams API it is now very convenient to return a lazily-evalua= ted stream of Model objects. It is also very convenient to make this stream= pull data directly from an underlying ResultSet, tronsforming each row on-= the-fly into a Model object. This, however, calls for holdable result sets = because the transaction commits when program control leaves the Service lay= er. >=20 > Having a holdable result set escape the service layer feels like a simila= r layering violation as having an open transaction escape the service layer= . Either way a heavyweight database object escapes and must be cleaned up = at a later date. Na=EFvely I would expect the cost of holding the two obje= cts to be similar, since the actual underlying transaction cannot commit/ro= llback until all results are read from the cursor? I do not propose this as a solution that reduces the overall cost and you a= re right that the cost would just migrate. On the other hand, note that Ora= cle and MS SQL Server provide holdable cursors by default; in fact, Oracle = supports nothing _but_ natively holdable result sets. >=20 >> The above could raise the level of interest of the PostgreSQL JDBC team = in implementing holdable result sets backed by native holdable cursors inst= ead of the current client-side cursors, which don't allow the space complex= ity to be reduced from O(n) to O(1) on the JVM side. I am aware that this i= s not a trivial endeavor as it requires intervention into the FE/BE protoco= l, but I would nevertheless propose that this concern be reassessed in the = light of new developments in the Java ecosystem. >=20 > As an alternate thought, Stream is AutoCloseable. What if we introduce a= StatementStream, which takes a (Prepared)Statement, executes in a transact= ion with small fetch size, and then returns a Stream. Again very pseu= do-codey: >=20 > class DAO { > Stream findObjects() { > return new StatementResultStream(conn, "SELECT * FROM objects"); // se= ts fetch size, ensure auto commit off > } > } >=20 > class JsonStreamOutput implements StreamingOutput { > StreamOutput(Supplier> streamSupplier) { this.streamSupplier = =3D streamSupplier; } > public void write(OutputStream os) { > try (JsonGenerator jg =3D new JsonGenerator(os); > Stream str =3D streamSupplier.get()) { > str.forEach(obj -> jg.writeObject(obj)); > } > } > } >=20 > @Path("/objects") > class Resource { > @GET > public StreamOutput getObjects() { > return new JsonStreamOutput(() -> dto.findObjects().filter(...).map(dt= o -> new TransformedDto(dto))); > } > } Here I'm not sure I follow you. Do you mean to have the transaction boundar= ies move from the controller into the View layer? Your StreamOutput-returni= ng controller method would just set up the fetch, then the framework layer = above it (which I call the View) would consume that, and only upon consumpt= ion would the Statement execute. You still seem to dictate the output format directly from the Controller, t= he avoidance of which is motivating my approach. > The StatementResultStream and StreamOutput classes are entirely reusable.= The DAO is no more complicated than before, except instead of using JDBC = directly you punt the work until the Stream undergoes a terminal operation.= The main difficulty here is figuring out a sensible API for StatementResu= ltStream construction. >=20 > The only bit I'm not happy with is the fact that you have to lift your in= termediate stream operations into a lambda. You might be able to avoid thi= s by instead writing the whole bit in terms of a Spliterator instead and us= ing StreamSupport.stream(spliterator), but that introduces questions about = held resources since Spliterator is not AutoCloseable. This is easily solved (I already do it for my ScrollableResultsSpliterator)= : Stream has an onClose hook, so you just introduce a close() method to the= spliterator and attach it to the hook. > This has the advantage that it's implementable today without changes to e= ither JDBC or PGJDBC, and introduces only reusable optional components to e= .g. Spring or JDBI or whatever library wishes to do this. >=20 > Thoughts? > Steven >=20 --=20 Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-jdbc