Skip to content

Bitstring, "char" type, parameter fixes. - #390

Merged
Emill merged 2 commits into
npgsql:masterfrom
Emill:bitstring-and-parameter-fixes
Oct 24, 2014
Merged

Emill merged 2 commits into
npgsql:masterfrom
Emill:bitstring-and-parameter-fixes

Conversation

@Emill

@Emill Emill commented Oct 19, 2014

Copy link
Copy Markdown
Contributor

This is based on pull request #362 and implements the following:

  • 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.

* 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.
@Emill

Emill commented Oct 20, 2014

Copy link
Copy Markdown
Contributor Author

Comments before merging?

@roji

roji commented Oct 20, 2014

Copy link
Copy Markdown
Member

Give me a day or so, OK? :)

Comment thread Npgsql/NpgsqlCommand.cs

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The order of appearance of the parameters in the query is not important. It is the order in the parameters collection that matters.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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!

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@franciscojunior franciscojunior mentioned this pull request Oct 20, 2014
@franciscojunior

Copy link
Copy Markdown
Member

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.
Another point I'm still checking is the setting of NpgsqlDbType of the parameters based on the type oid response from the server: https://github.com/npgsql/npgsql/pull/390/files#diff-2e2eb4df8b3bc293a4e964fec06556b2R493
Please, could you elaborate more about that?

Other than that, your work is excellent, @Emill !

@Emill

Emill commented Oct 20, 2014

Copy link
Copy Markdown
Contributor Author

Also, the following modified test from report #146 doesn't work:

It works for me, with or without a cast...

Another point I'm still checking is the setting of NpgsqlDbType of the parameters based on the type oid response from the server: https://github.com/npgsql/npgsql/pull/390/files#diff-2e2eb4df8b3bc293a4e964fec06556b2R493
Please, could you elaborate more about that?

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.)
For some reason, PostgreSQL does not like unknown parameter types (see https://github.com/postgres/postgres/blob/4cbe3abb3162d14a86bc8ec73fd9331638ec18a0/src/backend/commands/prepare.c#L119). A parameter type is considered unknown if we didn't specify a type oid and it couldn't infer the type. So I think this is the only reasonable thing to do (i.e. fail). If not, what type oid should we pass? We could pick something random (like string) but I think that won't make much sense either, because maybe later the user assigns an int value and that won't work. If this really happens for a user, the user should explicitly set the type of the parameter and it will be fine.

Comment thread Npgsql/NpgsqlCommand.cs

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@roji

roji commented Oct 21, 2014

Copy link
Copy Markdown
Member

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?

@Emill

Emill commented Oct 21, 2014

Copy link
Copy Markdown
Contributor Author

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...

@franciscojunior

Copy link
Copy Markdown
Member

It works for me, with or without a cast...

Hmmm, strange... Nevermind. It now works for me too. :) I think the problem was between the chair and the computer... :)

@franciscojunior

Copy link
Copy Markdown
Member

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...

Hmmmm, if a column is of type char(5) and the user tries to use a char(10), will it generate an error?

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.

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
it seems that sqlclient considers it an error if you call Prepare() without setting explicitly the types of all parameters, even the output ones.

So I think this is the only reasonable thing to do (i.e. fail). If not, what type oid should we pass? We could pick something random (like string) but I think that won't make much sense either, because maybe later the user assigns an int value and that won't work. If this really happens for a user, the user should explicitly set the type of the parameter and it will be fine.

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.

@Emill

Emill commented Oct 21, 2014

Copy link
Copy Markdown
Contributor Author

Hmmmm, if a column is of type char(5) and the user tries to use a char(10), will it generate an error?

Not necessarily, it will only generate an error if the right-trimmed input string is longer than 5 characters.

insert into tbl (testcol) values ('abc   '::char(6))

works but this does not:

insert into tbl (testcol) values ('abc   u'::char(6))

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.

it seems that sqlclient considers it an error if you call Prepare() without setting explicitly the types of all parameters, even the output ones.

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.

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.

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.

I just don't know yet if it is ok for sqlclient to use a parameter with type sqlvariant and pass a null value.

Yes it works. But sql_variant is not like unknown in postgresql, it is a separate type.

@franciscojunior

Copy link
Copy Markdown
Member

I wonder if we should not simply drop the Size field altogether.

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.
Please, correct me if I'm being too much simplistic.

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.

+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.

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.

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(). :)

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.

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.

Yes it works. But sql_variant is not like unknown in postgresql, it is a separate type.

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.

@Emill

Emill commented Oct 21, 2014

Copy link
Copy Markdown
Contributor Author

Please, correct me if I'm being too much simplistic.

I think you're correct.

+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.

So what should we do?

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 added in EF so that all parameters set the explicit DbType, since EF is statically typed, so this will always work.

@franciscojunior

Copy link
Copy Markdown
Member

So what should we do?

I just noticed the following in the SqlParameter.Size documentation:
"For variable-length data types, Size describes the maximum amount of data to transmit to the server. For example, for a Unicode string value, Size could be used to limit the amount of data sent to the server to the first one hundred characters."

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.
This also would fix the case you told before:

For the case with Char(big value), we then have to blank pad with a size that might be big...

We don't have to blank pad. We just would need to make sure that the value would fit in the big value.

I added in EF so that all parameters set the explicit DbType, since EF is statically typed, so this will always work.

Excellent!

@Emill

Emill commented Oct 21, 2014

Copy link
Copy Markdown
Contributor Author

For the case with Char(big value), we then have to blank pad with a size that might be big...

We don't have to blank pad. We just would need to make sure that the value would fit in the big value.

In SqlClient it works like this if the query is "Select @p": if the user specifies Char(10) as parameter type and sets the string "Hello", SqlClient will send only "Hello" over the wire, and specify the parameter type Char(10) to the backend. The backend will then notice that the string passed must be blank-padded to be 10 chars long, so it sends "Hello " over the wire. (In Github's markdown you only see 1 space, but it is 5.)

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...

@franciscojunior

Copy link
Copy Markdown
Member

In SqlClient it works like this if the query is "Select @p": if the user specifies Char(10) as parameter type and sets the string "Hello", SqlClient will send only "Hello" over the wire, and specify the parameter type Char(10) to the backend. The backend will then notice that the string passed must be blank-padded to be 10 chars long, so it sends "Hello " over the wire. (In Github's markdown you only see 1 space, but it is 5.)

Interesting. I didn't know the size would be used two-way.

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...

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?

@Emill

Emill commented Oct 21, 2014

Copy link
Copy Markdown
Contributor Author

Great! I also don't see any.

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).

Also, in our case, parameter size would be used only one way: from client to server.
Is this correct?

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.

@franciscojunior

Copy link
Copy Markdown
Member

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).

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.

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 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...

@Emill

Emill commented Oct 21, 2014

Copy link
Copy Markdown
Contributor Author

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 "Select bit_field from some_table".
However, if we want to be able to handle "Select :p1" where p1 is a parameter of type BIT and Size = 1, so it returns a bool and not a BitString, we have to append ::bit(1).

@franciscojunior

Copy link
Copy Markdown
Member

However, if we want to be able to handle "Select :p1" where p1 is a parameter of type BIT and Size = 1, so it returns a bool and not a BitString, we have to append ::bit(1).

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?

@Emill

Emill commented Oct 22, 2014

Copy link
Copy Markdown
Contributor Author

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).

@franciscojunior

Copy link
Copy Markdown
Member

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.

@franciscojunior

Copy link
Copy Markdown
Member

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).

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.
I saw you already have one which transforms bool values in 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?

@Emill

Emill commented Oct 23, 2014

Copy link
Copy Markdown
Contributor Author

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?

If a user writes a query like Select bit_1_field from some_table, then the type of the returned column will be bit(1) and therefore Npgsql will return a bool. The RowDescription message contains both type oid and type modifier (which is the size for bit type), while one in the Parse message can only describe type oid.

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.
I saw you already have one which transforms bool values in 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.

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.

@franciscojunior

Copy link
Copy Markdown
Member

If a user writes a query like Select bit_1_field from some_table, then the type of the returned column will be bit(1) and therefore Npgsql will return a bool. The RowDescription message contains both type oid and type modifier (which is the size for bit type), while one in the Parse message can only describe type oid.

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:

However, if we want to be able to handle "Select :p1" where p1 is a parameter of type BIT and Size = 1, so it returns a bool and not a BitString, we have to append ::bit(1).

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. :(

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.

Ahhhhhh, well, indeed I thought my idea was too easy to be true.... :)
Now I remember we had some problems with the downcasting of datatypes when handling the NpgsqlDateTime etc and others. :)
Thanks for the heads up!

@roji

roji commented Oct 23, 2014

Copy link
Copy Markdown
Member

Sorry to be a bit late to the party :)

I pretty much agree with all of the above.

I just noticed the following in the SqlParameter.Size documentation:
"For variable-length data types, Size describes the maximum amount of data to transmit to the server. For example, for a Unicode string value, Size could be used to limit the amount of data sent to the server to the first one hundred characters."
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.

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 SqlClient it works like this if the query is "Select @p": if the user specifies Char(10) as parameter type and sets the string "Hello", SqlClient will send only "Hello" over the wire, and specify the parameter type Char(10) to the backend. The backend will then notice that the string passed must be blank-padded to be 10 chars long, so it sends "Hello " over the wire. (In Github's markdown you only see 1 space, but it is 5.)
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...

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.

@roji

roji commented Oct 24, 2014

Copy link
Copy Markdown
Member

@Emill, I say merge this as soon as possible to avoid conflicts with other ongoing work (especially #388). We can always take care of the little bits later.

Emill added a commit that referenced this pull request Oct 24, 2014
Bitstring, "char" type, parameter fixes.
@Emill
Emill merged commit a0c74d6 into npgsql:master Oct 24, 2014
@Emill

Emill commented Oct 24, 2014

Copy link
Copy Markdown
Contributor Author

Ok. Done.

@roji

roji commented Oct 24, 2014

Copy link
Copy Markdown
Member

Great. Can you briefly say what remains to be done so we don't forget? Is the size behavior implemented etc...

@Emill

Emill commented Oct 24, 2014

Copy link
Copy Markdown
Contributor Author

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.

@roji

roji commented Oct 24, 2014

Copy link
Copy Markdown
Member

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.

@Emill

Emill commented Oct 24, 2014

Copy link
Copy Markdown
Contributor Author

Ok. I'll wait until #388 is done though.
Den 24 okt 2014 10:33 skrev "Shay Rojansky" [email protected]:

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.

—
Reply to this email directly or view it on GitHub
#390 (comment).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants