Repository navigation
Bitstring, "char" type, parameter fixes. - #390
Conversation
* BitString are now correctly returned from backend, and is correctly handled in parameters. * BIT(1) maps to the .NET bool type and other BIT maps to BitString. * Output parameters now work correctly for prepared queries. * DbType.Time is now mapped to interval. * The "char" type now returns a Char instead of a String. * Type OIDs are sent in the Parse message. * Optimizations when all format codes are the same in Bind message. * Automatically infer parameter value types when setting a value. * New NpgsqlDbType.Unknown that specifies that Npgsql should not try infer the value type, nor cast the value when written to sql, but simply write a literal string in text form.
|
Comments before merging? |
|
Give me a day or so, OK? :) |
There was a problem hiding this comment.
By using the parameters collection to populate the parameterTypeOids in a 1-1 mapping, you can get a problem when the same parameter is used more than one time in the query string. For example, in the following query:
select * from table where column1= :param1 and column2= :param1
or, you also could invert the order of the parameters:
select * from table where column1= :param2 and column2= :param1
There was a problem hiding this comment.
When I thought about this problem, my idea was to populate this parameterTypeOIDs collection from the procedure which handled the parameters substitution because there you would know which parameters were being used in the query and its order.
There was a problem hiding this comment.
The order of appearance of the parameters in the query is not important. It is the order in the parameters collection that matters.
There was a problem hiding this comment.
Excellent! I didn't notice that the parameter substitution logic already took care of the parameters mapping in the query string regardless of their position and/or repetition when preparing the command. Parameters in the prepared query are numbered in the same order as they appear in the parameters list! Sweet!
There was a problem hiding this comment.
One more comment (maybe I'm confused). What happens if this is a function call and some parameters are OUT parameters? If we're only sending OIDs for input parameters can't the order get confused?
There was a problem hiding this comment.
Therefore the IsInputDirection check. In the parameter substitution logic, the number each input parameter get is the index of input parameter in the parameter collection. So it will be correct. This was not handled correctly before.
|
Some tests I played with which aren't working: I noticed that if you don't specify neither a datatype or a value for the parameter, the query fails when prepared. For example: [Test]
public void ParameterNullValueNoDbType([Values(true, false)] bool prepareCommand)
{
using (var cmd = Conn.CreateCommand()) {
cmd.CommandText = "Select :a";
cmd.Parameters.Add(new NpgsqlParameter() { ParameterName = "a" });
if (prepareCommand)
cmd.Prepare();
using (var reader = cmd.ExecuteReader()) {
reader.Read();
}
}
}Doesn't work when prepared because we can't give any information to the server from the null value and the server also doesn't seem to be able to do anything with the null value. Also, the following modified test from report #146 doesn't work: [Test]
public void ParameterNoDbType([Values(true, false)] bool prepareCommand)
{
using (var cmd = Conn.CreateCommand()) {
cmd.CommandText = "SELECT @0";
var par = cmd.CreateParameter();
par.ParameterName = "0";
par.Value = 1;
cmd.Parameters.Add(par);
if (prepareCommand)
cmd.Prepare(); // exception fires error 22021: invalid byte sequence for encoding „UTF8“: 0x00
cmd.ExecuteScalar();
}
}I removed the manual cast it was being done. If I put back the manual cast, the error reported happens. I think those are some really really edge cases which we need to fix. Other than that, your work is excellent, @Emill ! |
It works for me, with or without a cast...
Check the example on line 4100 in CommandTests.cs: https://github.com/npgsql/npgsql/pull/390/files#diff-d00d89f70ac53244e7449ab9e43ec7c2R4100. Here it is the database backend that finds out which type to use, since the user didn't specify anything. If the parameter value is later changed, we will make sure to only accept values of the correct type, and also when sending the value, it will be sent in the correct format. If the database backend couldn't infer a type (when we sent no type oid) by looking at the context, it will throw an error as in your first example (ParameterNullValueNoDbType). In that example, there isn't really anything to do. (It doesn't work in the current master either.) |
There was a problem hiding this comment.
This code should probably be Linqified, something along the lines of:
var parameterTypeOIDs = _parameters
.Where(p => p.IsInputDirection)
.Select(p => p.TypeInfo.NpgsqlDbType == NpgsqlDbType.Unknown ? 0 : _connector.OidToNameMapping[_parameters[i].TypeInfo.Name].OID)
.ToArray()There was a problem hiding this comment.
I'd like to, but if we strive for zero allocation that is not an option.
That example would make at least 7 allocations.
3 enumerator objects.
2 lambda function objects that contain captured variables.
ToArray doesn't know in advance how many elements to put in the array, so
it creates a buffer which size is doubled and copied on overflow and
finally copies all elements to a new destination array.
We also get function call overhead.
Den 21 okt 2014 10:41 skrev "Shay Rojansky" [email protected]:
In Npgsql/NpgsqlCommand.cs:
@@ -423,32 +423,78 @@ void PrepareInternal()
_preparedCommandText = GetCommandText(true); NpgsqlRowDescription returnRowDesc = null;
ParameterDescriptionResponse parameterDescription = null;
var numInputParameters = 0;This code should probably be Linqified, something along the lines of:
var parameterTypeOIDs = _parameters
.Where(p => p.IsInputDirection)
.Select(p => p.TypeInfo.NpgsqlDbType == NpgsqlDbType.Unknown ? 0 : _connector.OidToNameMapping[_parameters[i].TypeInfo.Name].OID)
.ToArray()—
Reply to this email directly or view it on GitHub
https://github.com/npgsql/npgsql/pull/390/files#r19135562.
|
I'm not an expert on the parameter type system but everything looks better now. So apart from the minor notes I posted it looks really good to me. All tests pass on my machine as is. BTW, just to make sure I understand everything: once we switch non-prepared parameterized queries to the extended protocol (#370), the whole NpgsqlParameter.UseCast mechanism is no longer needed, right? |
|
That's true. Just one note: if the user specified a size of the parameter, we should honour this. What I do now is to add an explicit cast for those cases, like ::char(123), which will make the backend either truncate it or enlarge it. SqlClient truncates the string as well, but client side (it still sends the size of the parameter to the backend, but Postgresql only accepts type oid, not size). So an option to this would be to truncate or enlarge strings and bitstrings on the client side, and avoid the cast. What do you think? For the case with Char(big value), we then have to blank pad with a size that might be big... |
Hmmm, strange... Nevermind. It now works for me too. :) I think the problem was between the chair and the computer... :) |
Hmmmm, if a column is of type char(5) and the user tries to use a char(10), will it generate an error?
I checked it. Well, I think this will be a feature of Npgsql which doesn't exist in the sqlclient. :) From this thread: http://stackoverflow.com/questions/14279116/sqlcommand-prepare-method-requires-all-parameters-to-have-an-explicitly-type-set
I'm more inclined to use a oid of text for the unknown types. This would avoid those type of errors because. For example, if the user tries to insert a null value, she may face this error. From the fact that sqlclient doesn't allow Prepare to be called without specifying all parameter types explicitly, I think we may not face any report about that. We may receive some report if a user forgets to set the parameter type and pass a null value. In the past, we indeed used string datatype. That's why you may have seen in the parameters that it defaulted to String. Now it defaults to Unknown. I think we may handle this type similar to sqlclient's SqlVariant. I just don't know yet if it is ok for sqlclient to use a parameter with type sqlvariant and pass a null value. I think this is a very edge case. |
Not necessarily, it will only generate an error if the right-trimmed input string is longer than 5 characters. works but this does not: I wonder if we should not simply drop the Size field altogether. It is necessary for use with SqlClient, since MS SQL Server doesn't accept non-sized (n)varchar/char parameters. But for PostgreSQL it is quite useless. And I think throwing an exception is better than truncating the string (SqlClient truncates with no exception), if PostgreSQL finds out that the value is too big to store in a sized column.
Yes I've noticed that. That is kind of strange since the type can almost always be inferred by the type of the value. And this is only for prepared statements in SqlClient, not normal statements, even though they use about the same mechanism when sending the data over the wire.
If the user is inserting a null value into a database, this approach will work, since postgresql will then figure out which type the column is of. If we set oid to text, then a null value (of type text) can't be inserted to a field of type int4. The case "Select :param1" is very rare I think.
Yes it works. But sql_variant is not like unknown in postgresql, it is a separate type. |
This is good point. From what you said, and even from the protocol itself, it seems, the size isn't very important. It will only matters in the end when the server tries to store the value and checks if it fits in or not.
+1 to throw an exception if the user tries to insert a value too big to store in a sized column. But I think this will be a very polemical topic as there will be users who would prefer that Npgsql silently truncate the data.
I think the idea of sqlclient prepare method would be to gather as much information as possible to increase the performance of the code. So, when preparing the code, they kind of short circuit any type of parameter inference or apply a lot of shortcuts to get the code read to be run as fast as possible. From this discussion and from the communication protocol, Postgresql uses another approach. Given the protocol support you implemented, @Emill , I think Npgsql will have a more elaborated version of Prepare() (related to sqlclient Prepare()) where users will be able to use it to get parameter datatypes and that Npgsql won't need to have all the parameters types specified by the user before calling Prepare(). :)
I see. You are right. I also think this case will be very rare. I think users would rarely use a construction like that. My concern is with queries created by EF, for example. But as all tests from our testsuite pass, I think this won't be a problem.
I see. I thought about comparing them because I think we are using the NpgsqlDbType.Unknown the same way as sqlclient uses the SqlVariant when the user doesn't specify a data type yet for a parameter. |
I think you're correct.
So what should we do?
I added in EF so that all parameters set the explicit DbType, since EF is statically typed, so this will always work. |
I just noticed the following in the SqlParameter.Size documentation: So, this explains why sqlclient truncate the value. Under this new reading, I think we should do the same and treat size as the maximum data we should transmit and truncate data if needed.
We don't have to blank pad. We just would need to make sure that the value would fit in the big value.
Excellent! |
In SqlClient it works like this if the query is " So in our case, only if we write $1::bpchar(10) in the query, will we get the same behaviour. But I don't see any particular use case for this... |
Interesting. I didn't know the size would be used two-way.
Great! I also don't see any. So, if I understood correctly, we can mimic the way sqlclient handles the size property and use it as the maximum length of the data which will be transfered to the server, which would effectively truncate data if the size is shorter than data length. Also, in our case, parameter size would be used only one way: from client to server. Is this correct? |
So do you think we should drop the ::bpchar(size) cast to blank-pad the string if it is smaller than the given size? Note that this also corresponds to the BIT type (zeros are added in the end).
In the case for BIT(1), then the size is actually used. If size is 1 for BIT, then a bool is returned to the user, othertwise a BitString is returned. But then it is the type modifier of the column of the RowDescription that is used. |
I think so. Based on the Size documentation, I understand that it is used to specify the max length to be sent. There is no indication about the need to pad the parameter value to match the specified size. In fact, I couldn't find any information about the Size property bigger than parameter size. :( I hope I'm not rushing this too much. Maybe we need to make some more tests to check if everything works ok without the size casts.
I see. But this happens because we wanted to handle bit(1) this way, right? I mean, this BIT(1) value returned wasn't returned this way because we specified ::bit(1) as the parameter cast, or was it? And if we didn't specify it this way it would work... |
Correct, it is usually returned this way because the column comes from a field of type bit(1) when a user runs a query like " |
Hmmmmmm, this cast need to make the bit(1) be returned as bool makes me think the following: What if we drop this requirement (need to use a cast to get the bit(1) as bool) and return everything as bitstring and we provide an explicit cast operator for BitString datatype to be handled like bool if it only has a single bit value? As the postgresql already has the boolean datatype, I think there woundn't need to have another synonym for bool type. This would allow us to get rid of this casting around datatypes, unless strictly necessary. (The only case where this would be strictly needed seems to be #255 ) I know I already gave +1 for the bit(1) as bool, but I'm changing my mind when I think the possibility of solving this datatype conversion directly in the BitString type. What do you think? |
|
I think we should use .net bool for bit(1). The reason is compatibility with other databases. If the user copies their table definitions from other systems which uses bit(1), the behaviour should be equal to other ado.net providers (i.e. use .net bool). |
I see. And I agree with you. I just thought we could solve this compatibility in the BitString data type instead of forcing the cast in the backend. But I think we can have this ::bit(1) cast as an example of a strictly necessary cast. |
Ok, let's recapitulate: I can see that when sending the parameter bool to a bit field, it is converted to 1 or 0. So far, so good, in terms of compatibility. The issue arise when getting data back from the database. Currently, we would need a cast to ::bit(1) to get a boolean value back, right? What if we add an explicit operator bool to BitString which would convert a Bitstring with length 1 to boolean? This way, we wouldn't need the cast, all bit datatype would be returned as Bitstring. If the user calls NpgsqlDataReader.GetValue(int) he would be able to cast it to boolean transparently and we gain the fact that we would handle this BitString particularity in the BitString type itself without having to use database casts. Our backend/frontend converters would be simpler too. What do you think? |
If a user writes a query like
Well I tried to do something like that with both an implicit and explicit cast operator, but failed. See the http://stackoverflow.com/a/4393569 post. Internally, the objects are of type System.Object. Even though we define cast operators from BitString to bool, downcasted BitStrings cannot be converted to bool. |
Ok. I thought you would need the cast ::bit(1) in order to get the oid and typemodifier in place for the correct conversion. By rereading your text:
I see that the cast would only be needed to satisfy the "Select :p1" query and not all the queries involving bit(1) fields. My bad. I misread it. :(
Ahhhhhh, well, indeed I thought my idea was too easy to be true.... :) |
|
Sorry to be a bit late to the party :) I pretty much agree with all of the above.
I agree with @franciscojunior here. I guess we can view the Size setting as an optimization option for the user: maybe that already have a big byte[] but only want to send part of it to the backend, without copying it client-side. This obviously has some considerable interaction with #385 (and also #370), it may be better to wait until those are complete.
In general, I think we should try hard to eliminate all cases where we rewrite the query with special casts. After #370 we won't have client-side binding anymore, and can simply get rid of any query rewriting (except for setting changing the parameter character to $). This would make Npgsql much less invasive, minimal and complicated. More specifically, @Emill, I agree with you that doing ::bpchar(10) doesn't make sense just to do space padding - it just doesn't seem important enough. It seems OK to have limits on compatibility with SqlClient. IMHO the same goes for "SELECT :p1" with BIT(1) - rewriting the query just to allow for the case to provide a bool seems extreme. |
Bitstring, "char" type, parameter fixes.
|
Ok. Done. |
|
Great. Can you briefly say what remains to be done so we don't forget? Is the size behavior implemented etc... |
|
The behaviour for the user is the same as in SqlClient. Right now truncation and blank padding is done on the backend, by adding ::type(size). Truncation could be added on the client side but blank padding on the client side seems like a bad idea. |
|
OK, great. When you have time to do the client-side truncation I guess that would wrap this up. I agree that blank padding is a non-issue, we can drop it. |
|
Ok. I'll wait until #388 is done though.
|
This is based on pull request #362 and implements the following: