Repository navigation
Description
Hi everyone.
There's something that was bugging me for a while now - the use of text to transfer data to and from the backend (we've had discussions about this before). In a nutshell, since we use the Postgresql simple query protocol, and that protocol only supports results in text, we're stuck parsing text that in many cases is also locale-dependent. We've gotten around it up to now mainly by switching to culture-invariant locale, but we still have problems such as #324, #266, #163 and many other potential ones. The situation is even worse with nonprepared (i.e. client-side) parameterized queries, since we have to encode data into text, again possibly running against locale issues.
The extended query protocol allows specifying both binary output and input, which eliminates this problem and also improves performance (think of nonprepared parameterized queries, we we encode a number into text and send it, just to have the backend decode it back into a number...). While I thought about going binary-only, I thought that with the extended protocol you have to do several roundtrips (PARSE, BIND, DESCRIBE, EXECUTE, SYNC), which would be unacceptable in terms of performance.
So I went ahead and sent the question to the Postgresql devs. The answers I got say very simply that we're supposed to use the extended protocol, but to send all our messages in one packet, eliminating the roundtrips. In addition, the extended protocol optimizes for "unnamed" statements and portals in a way which makes it perfect for non-prepared statements.
In other words, I think I now understand that the simple protocol is simply not meant to be used the way we're using it... Here's what we could do:
- Simple nonparameterized queries are implemented as PARSE, BIND, DESCRIBE, EXECUTE, SYNC, all in one packet - results in binary.
- Non-prepared parameterized queries send the parameters to the server, exactly like prepared statements, except that the unnamed statement and portal are used (this optimizes for single-use at the backend). Note the change: npgsql's role is reduced to substituting @param1 to $param1, we no longer have to deal with any sort of escaping (if I understand correctly). I think this in itself is an advantage
- Prepared queries are sent like today
One thing: the only thing not supported by the extended protocol is sending multiple queries in one go (SELECT 1; SELECT 2). This can be easily implemented inside Npgsql with several queries.
Pros:
- Eliminate the entire textual processing path, we maintain only binary rather than maintaining two paths. No more text parsing or formatting anywhere, the code base is smaller and simpler.
- No more locale issues for parameters or return values, ever.
- Improved performance (no more passing through text)
- Non-prepared parameterized queries are simplified (parameters sent to backend so no need to escape, etc.)
Cons:
- All data types need to be implemented in binary (this isn't the case currently)
- Big change
@franciscojunior, @jbcooley, @glenebob, @Emill, could I have your opinions on this? I'd be happy to do the implementation if you think it's a good way forward.
Activity
Emill commentedon Sep 29, 2014
Sounds interesting. If there are no parameters however, I think we should
still use the simple query.
I wonder though how error messages would work, for example if Parse throws
an error, we have already sent the next messages.
glenebob commentedon Sep 29, 2014
Emill,
That's what the Sync message is for. When PG throws an error, it fast
forwards to the Sync message, then begins processing again on the next
message. Any messages between the one that failed and the Sync are ignored.
-Glen
glenebob commentedon Sep 29, 2014
I think this is a great idea. And browsing the code just now, I see that I
didn't go far enough when I refactored the Prepare/Execute code. It could
all be done in only one round trip. I think it would be pretty simple to
refactor a little more, such that Parse and Execute are sent in one go, as
describe here. Basically, move the code in PrepareInternal() into
GetReader(). If need prepare, send Parse and Describe,. then send the
Execute messages, then look for row description IF Describe was sent.
Copy/paste mainly.
But I think before we go forward with this, we need to be sure we're not
hurting performance. I don't think Npgsql's extended query path is as fast
as simple. I got it close, but not quite there. Let's do the refactor I
just described, and then benchmark the heck out of it against the simple
path, before doing anything else. Only after we're able to match or exceed
the simple parth's performance should we consider removing the simple path.
I also think we could look at an alternate method of parameter processing:
Old vs new. If users used the ordinal parameter encoding that PG
recognizes, I think we could eliminate the overhead of query parsing on our
end.
More comments below...
On Mon, Sep 29, 2014 at 6:09 AM, Shay Rojansky [email protected]
wrote:
Maybe I'm missing something with the locale issue (it's easy to do when
you've lived and worked your entire life, essentially, in the invarient
culture), but why would we use anything but the invarient culture for
moving data between Npgsql and PG? Seems like a non-issue to me.
-Glen
roji commentedon Sep 29, 2014
Yep, @glenebob is absolutely right about the errors - this is also what the Postgresql people explained.
The problem with this, is that simple query always means text results - which we need to parse. This would mean keeping the entire textual parse path, along with all the localization problems and the rest... The motivation here (for me) is to really cut the whole thing out with the extended protocol, and not just improve the non-prepared parameterized queries...
Emill commentedon Sep 29, 2014
I think there is one problem. If we send all messages at once, i.e. Parse,
Describe, Bind, Execute, Sync, we don't wait for the response from Describe
that tells what data types will be returned, which means we can't decide
which output columns should be sent as binary and which to send as text.
glenebob commentedon Sep 29, 2014
Hmm, good point, but I think it's solvable by simply taking a different
path when we have output parameters, getting the response from Describe
before continuing, and then not expecting such a response after completing
the send operation.
-Glen
Emill commentedon Sep 29, 2014
I was thinking about normal queries without output parameters, (but the
same probably applies if we have output parameters). If we want only one
round trip, we must still specify how the columns should be returned (text
or binary). Since we don't know how many or which data types the columns
use, we must either say that everything should be returned as text or
everything should be returned in binary. @roji, did the PG guys say
anything about this?
Den 29 sep 2014 22:02 skrev "Glen Parker" [email protected]:
roji commentedon Sep 29, 2014
Hey guys, was away for a while. Thanks for the serious discussion. I think I need to explain my understanding of things better (it may also be wrong).
@glenebob, I'll explain the problem we're facing the problems as I see them. Since parameters and results are sometimes transferred in text mode, we have to set culture-invariant locale for dates, money, etc. However, this special setting (which npgsql forces on the our users) also affects other things, such as built-in Postgresql functions that do things with dates and money: In #266 a user complains that SELECT to_char(100.99,'FML999,999.00') doesn't return a dollar sign as expected. In other words, our choice of encoding as text causes us to modify Postgresql's behavior in a way that the user didn't request and doesn't want.
#324 is somewhat different: due to the nature of floats/doubles, conversion to and from text necessarily loses precision. Again, to counter this we set extra_float_digits to 3, affecting all kinds of Postgresql operations. For example, if the user does SELECT format('%s', 0.28::double precision), they get 0.280000000000000027 instead of the expected 0.28. They didn't ask to set extra_float_digits to 3, we did it for them because we transfer doubles/floats in text.
I'm trying to say that the fact that we need to support any sort of text encoding of money, double, dates causes some extreme difficulties that are very hard to solve in a definite and sane way.
That doesn't mean I want to transfer everything in binary, but it seems like I have no choice. @Emill's last comment is correct: the problem is how to handle result types. The BIND command allows you to specify either binary for text for result columns; this can be done either by column, or for all columns (this is very clear in section 48.2.3 of the manual). But we have no idea what result columns are returned - think "SELECT * FROM data" - no way of knowing anything about the results. Therefore, the option of specifying text/binary per column seems out of the question. We're left with saying "please send all results in text" or "please send all results in binary".
So it's not that I want binary for all types for performance reasons or anything. It's simply that we can't pick and choose text and binary for result columns - we have to determine one or the other in advance, for all columns. Basically if you want to eliminate text encoding for some types, I think we have no choice but to eliminate it for all types. If we switch to the extended query protocol but continue using text, we will have gained little.
In addition, switching return data to binary also helps performance since results for all query types are now also transferred in binary, and not just prepared statements. For numbers this can be pretty important, for others less so. Regardless, I totally agree that performance tests are extremely important for everything here.
@Emill, you wrote:
The way it works is, is that you send all these messages in one packet and sit waiting for response messages. The first will be ParseComplete, then RowDescription, BindComplete, etc. In other words, we send all the message at once, but we still receive results in order. So we do get the response to describe (i.e. the RowDescription) before any actual row data is received, and can properly interpret the results.
@glenebob, you wrote:
I totally agree with the sentence "whether or not we use a named portal" - that would be the only difference between prepared and non-prepared parameterized queries. However, it's worth mentioning that both query types "do something with the backend" in the sense that they bind parameters at the backend (with the BIND message), and never actually place parameter values inside the query text at the frontend.
Emill commentedon Sep 29, 2014
Hmm..
If we do something like SELECT format('%s', $1::double precision) and send
$1 as 0.28 in binary and have extra_float_digits set to 3, doesn't that
mean we still get 0.280000000000000027?
I think it can be hard to do everything in binary. Now we accept datatypes
that are unknown to npgsql - the text representation will simply be
returned as a string to the user, which is usually ok. Otherwise we will
send a binary blob to the user if we use binary for everything, which the
user might not know how to interpret.
2014-09-30 0:46 GMT+02:00 Shay Rojansky [email protected]:
roji commentedon Sep 29, 2014
The point is that if we send (or receive) 0.28 in binary, we no longer have any reason to set extra_float_digits to 3 - this setting doesn't affect binary encoding in any way, only display (i.e. text). So the user is free to set extra_float_digits to whatever they want, we no longer care about it. Same thing with lc_monetary, DateStyle - binary means we no longer care about any of these things.
Maybe there's something here I don't know or understand, can you give an example of such a type that is unknown to npgsql?
The way I see it, in the current situation many types are implemented twice: once in text (because we have to, for simple queries) and once in binary - for performance (e.g. int). Unfortunately the binary encoding can't be used in simple query protocol, so performance suffers.
What I'm proposing is to have only one implementation for each type - in binary. I might be underestimating the effort here, but it doesn't seem outrageous that Npgsql implement all Postgresql binary types? Is it really that much better/easier to implement parse strings rather than binary data?
Emill commentedon Sep 29, 2014
Good point.
Try open the table pg_type in pg_catalog in the postgres database. Then you see a lot of data types, such as:
int2vector, regproc, oid, tid, xid, cid, smgr, reltime, tinterval, aclitem, any, void. I don't know what all of these are or if anyone need them. We have also seen newly added types such as json, hstore that was automatically treated as string by default (when Npgsql doesn't know the type, string is used), and therefore kind of worked "automatically" even if the user's current Npgsql version didn't support them.
Yes. If Npgsql has binary encoding for all types, then that would be the best, I think. I haven't benchmarked strings vs. binary so I can't say anything about performance. But I assume for things like bytea if there is a large amount of data, binary encoding is much better. But for things like integers, I don't know really. Remember that each binary parameter has a header of 4 bytes (length), followed by payload (4 bytes for int4). This probably means in the general case that extended queries use more network traffic. We should benchmark simple queries vs. extended queries to find out what the best is.
roji commentedon Sep 30, 2014
That's a very valid point. I sent another question to the postgresql-hackers list. I think the actual usable types which have a truly distinct binary encoding won't be many (i.e. arrays show up in pg_type as another type, but it isn't from the point of view of encoding). About unknown types I don't know, it's an excellent question. Let's see what they say.
Looking at the DataRow definition in the manual, it seems every data value has the 4-byte length - so this doesn't look different between text and binary encoding.
Regarding the payload, I think @glenebob already confirmed that binary performance for numbers is better (after all we currently do it with prepared statement parameters). It's true that if you have an int8 field, and use it to store only single-digit numbers, text encoding will produce smaller payloads. But if you're storing larger numbers, binary will produce smaller payloads (int4 will always by 4-byte in bytes, but can be easily be 6 bytes in text).
Regarding other values, I find it difficult to imagine cases where binary performance is going to be significantly worse (or at least significantly worse in most cases). After all the whole point of binary encoding in the world is to be efficient :) It's true that in many cases it won't matter (same performance more or less), but that's not an argument against doing binary...
10 remaining items
roji commentedon Oct 28, 2014
I was looking through some MSDN documentation and stumbled across an interesting fact.
We currently rewrite the query text to replace parameter placeholders: the user can supply parameters with @, while Postgresql expects parameters with $.
However, this ADO.NET page, says:
Note that according to the table there, SqlClient, Oracle, and OleDb/Odbc all have totally different placeholder schemes: the characters differ (@, ?, :), as well as the support for named vs. positional parameters. This means that we are not expected to go over the user's query and rewrite anything, the user is expected to write their placeholders in the Postgresql syntax.
Along with the rest of this issue (stop doing client-side parameter binding entirely), it's tempting (at least for me) to also remove placeholder rewriting and require users to use $. This would mean we stop messing with users' queries, forever - Npgsql becomes a simple, clean pass-through.
The (only?) downside is that this would probably be the biggest source of breakage, as all existing code that uses @ breaks. I'm not sure exactly what my opinion is, since we're already introducing breakage this may be the moment to do this - or it may be too much. What do you think?
roji commentedon Oct 28, 2014
Note request by user in #305 to implement named parameters, which doesn't seem possible at with Postgresql (see my response there).
Emill commentedon Oct 28, 2014
Just dropping : and @ would add too much breakage, I think. Maybe by adding connection parameters whether this should be supported or not.
I actually think named parameters are nicer to use than numbered, since it's harder to make mistakes when you can refer to a parameter.
The parameter-processing code is already written so I see no harm to use
it...
roji commentedon Oct 28, 2014
@Emill, I guess I agree - dropping it would be too much breakage (v3.0 already has enough).
franciscojunior commentedon Oct 28, 2014
I also agree that dropping this support would be too much breakage. A lot of queries would need to be rewritten which would cause a lot of problems.
Removed client-side parameter binding