Skip to content

Problems with bitstrings #335

Closed
Closed

Description

@Emill

From https://groups.google.com/forum/#!topic/npgsql-help/OAdtmKfCQ_o

I found out there are many problems with "bit varying" in Npgsql, although there is a BitString class.
First, Npgsql only seems to support bit which means bit(1), and not bit varying. I can't at least find a working type in NgpsqlTypesHelper.cs.
If you don't prepare the statement, and specify the data type as NpgsqlDbType.Bit, the bitstring is first written as a bitstring and then cast to a bit, like this: (B'0101101'::bit), which means it only takes the first bit (= 0).
When you prepare the statement, the text representation is written incorrectly, it is written as B'0101101' when it should only be 0101101 or some of the following versions:
0101101
B0101101
b0101101
If the length is a multiple of four, it can also be written in hex like
Xa01bc
xa01bc

The problem is that the convesion function at https://github.com/npgsql/Npgsql/blob/f6a7fed0b9bdaa0d1e31308d35bfb591e615b9fa/Npgsql/NpgsqlTypes/NpgsqlTypeConvNativeToBackend.cs#L372 doesn't check the parameter forExtendedQuery. If this is true, it should write the string according to one of the formats above. If it's false, it means it should write a literal bitstring to be put in a normal sql query (like it does now).

Activity

  1. Emill commented on Sep 7, 2014

    @Emill
    ContributorAuthor

    There should be a type in Npgsql "bit varying" or "varbit" so a cast can be done correctly.
    I don't know how to handle types of bit(N), like bit(9), which is a bitstring of length 9.

    FYI, select B'11101'::bit(9) returns 111010000.

  2. Emill commented on Sep 7, 2014

    @Emill
    ContributorAuthor

    Hm, maybe it's only the cast that is done wrong, when written as ::bit. If it instead is written as ::"bit", the value will not be truncated.

    select B'1101'::"bit" returns 1101, as expected.

  3. Emill commented on Sep 7, 2014

    @Emill
    ContributorAuthor

    In fact, I think we never need to do a cast if we know that the constant/literal already has the correct type, since it then becomes redundant.

  4. roji commented on Sep 7, 2014

    @roji
    Member

    Just a thought: in extended query mode (prepared), shouldn't the representation be binary rather than text?

  5. roji commented on Sep 7, 2014

    @roji
    Member

    One more thought: .NET has a BitArray class. Is there any reason we're using the custom Npgsql BitString rather than .NET BitArray?

  6. roji commented on Sep 7, 2014

    @roji
    Member

    At least one issue with BitArray is that it's non-generic, so boxing/unboxing..

  7. franciscojunior commented on Sep 7, 2014

    @franciscojunior
    Member

    BitString class was created a long time ago by Jon Hanna. At the time we didn't have support for binary types and so it was more used like a string datatype.

    Just a thought: in extended query mode (prepared), shouldn't the representation be binary rather than text?

    Yes. But I think we didn't add support for that though :(

    One more thought: .NET has a BitArray class. Is there any reason we're using the custom Npgsql BitString rather than .NET BitArray?

    Hmmmmm, it's been a long time since I talked to Jon Hanna about it. I think we would need to ask him. Let me see if I can find his user name so we can add him to this conversation...

  8. franciscojunior commented on Sep 7, 2014

    @franciscojunior
    Member

    Hi, @hackcraft, I hope you still remember me and the Npgsql project. I know it's been a long time, but would you mind to shed us some light about the BitString class and help us in this discussion? Thank you very much in advance.

  9. JonHanna commented on Sep 8, 2014

    @JonHanna
    Contributor

    I have no idea why I didn't use BitArray!
    IIRC, BitArray can be slower than ideal on iterating, due to its pre-2.0 enumerator, but whether I was thinking of that at the time, or something else, or just forgot that BitArray existed, I can't recall.

  10. franciscojunior commented on Sep 8, 2014

    @franciscojunior
    Member

    Thank you very much for your feedback, @hackcraft ! That information about the performance of BitArray is very welcome.

  11. franciscojunior commented on Sep 8, 2014

    @franciscojunior
    Member

    Just a thought: in extended query mode (prepared), shouldn't the representation be binary rather than text?

    I can see that the BitString has support to convert the string value to a byte[], so I think we could use that to send the data. We would just need to check what format Postgresql expects to receive a varying bit column value in binary form.

  12. Emill commented on Sep 8, 2014

    @Emill
    ContributorAuthor

    "documentation" for varbit_recv: http://doxygen.postgresql.org/varbit_8c_source.html#l00603

    Seems to be first a 32-bit integer length (containing number of bits) and then the data (8 bits per byte, big endian). If the bitlen is not a multiple of 8, the low bits in the last byte can be anything (they are discarded).

    When the database sends in binary, the format is the same, i.e. first 32-bit integer: number of bits, then the bits in big endian (padding bits in the last byte (the lower bits) will be 0).

  13. franciscojunior commented on Sep 8, 2014

    @franciscojunior
    Member

    Excellent!
    This will help us to get the data properly sent to the wire. :)

  14. 6 remaining items

  15. glenebob commented on Sep 10, 2014

    @glenebob
    Contributor

    Don't the speed tests suppress binary encoding so we can get a binary vs non-binary comparison?

  16. roji commented on Sep 11, 2014

    @roji
    Member

    It seems very unlikely that binary encoding wouldn't produce a pretty huge performance improvement over text... In cases where lots of data is being passed back and forth (e.g. lots of numbers), conversion to and from text must add considerable overhead... But it's true that this can be measured in the speed tests.

    @glenebob, I think you're the one who best knows what's going on there. Can you tell us which types are currently sent and received as binary?

    Am opening a different issue to discuss general binary type support.

  17. JonHanna commented on Sep 11, 2014

    @JonHanna
    Contributor

    IIRC, some people have found with postgres generally that binary encoding doesn't give as much a gain as they'd hoped largely because a lot of data in a lot of use-cases tends to be either textual or integers with values < 10,000 which end up being about as compact in the text encoding, and transfer time tends to predominate processing time.

    That said, there's no reason why one shouldn't see for oneself.

  18. glenebob commented on Sep 11, 2014

    @glenebob
    Contributor

    As I recall, the data types I implemented binary encoding for saw significant performance improvements. Bytea was already done and was far faster than text, and I added byte, int2, int4, int8, float4, and float8. All those types are simple conversions to/from network byte order, and so
    are as efficient as it gets (at both ends of the pipe), and they are very fast compared to text codecs, despite the increased network bandwidth for smaller numbers.

    I attempted to implement a binary codec for decimal types, and failed to achieve a net performance gain, because the binary representations do not match between .NET and Postgres, so I gave up. Maybe someone else can achieve a gain, but I'd be surprised if it's very impressive.

    There's good potential for gain with any types that composite integer or float types, such as points and rectangles. I did not implement those because I doubt they'd see heavy use. They would be very easy if anyone wants to dive in.

    The most impressive gain I achieved was in the binary array codec. I'm not sure how heavily arrays are used in the wild though, so the gain may be more academic than anything.

    Besides the difficulty in achieving performance gains when binary representations don't match, you must also consider portability. While integer and float binary representations won't be changing anytime soon, most other types are actually fairly likely to change. IMO binary codecs
    should be avoided for most types.

    My $0.02 :)

    -Glen

  19. roji commented on Sep 12, 2014

    @roji
    Member

    Thanks for the explanation @glenebob. Once again I think I was confused, I wasn't aware that you already implemented binary encoding for the important/basic numeric types :) These are obviously the most important ones and like you say, it's hard to believe binary encoding wouldn't result in a very significant speedup.

    One quick note regarding the portability aspect: I'm not sure what guarantees Postgresql provides, but it seems very unlikely that they would break something so fundamental within a single major release. We have our unit test suite running on the build server for each major version separately, so we would detect any sort of issue immediately. So IMHO portability doesn't seem like a strong argument against implementing binary types. The only drawback seems to be supporting multiple binary codecs based on backend version, which would probably require a refactor.

    A quick look at NpgsqlTypesHelper shows that the following types don't yet have a binary codec and could benefit from it:

    • The date/time/interval types. If this is easy/possible the performance gains should be considerable.
    • bit (this is partially what this PR was originally about)
    • numeric (may be useless according to @glenebob)
    • The "complex/high-level" types (e.g. point/circle/polygon), I agree with @glenebob here that these should be last priority because they're somewhat exotic.
  20. franciscojunior commented on Sep 13, 2014

    @franciscojunior
    Member

    Thanks for the explanation @glenebob. Once again I think I was confused, I wasn't aware that you already implemented binary encoding for the important/basic numeric types :) These are obviously the most important ones and like you say, it's hard to believe binary encoding wouldn't result in a very significant speedup.

    I think we have to take into consideration that some of this gain could be credited to the change we handle the data inside Npgsql. Before we were handling data internally as string and then converting them to byte[] and vice-versa. Now we handle them as byte[] and send those bytes directly to the wire.

    One quick note regarding the portability aspect: I'm not sure what guarantees Postgresql provides, but it seems very unlikely that they would break something so fundamental within a single major release. We have our unit test suite running on the build server for each major version separately, so we would detect any sort of issue immediately. So IMHO portability doesn't seem like a strong argument against implementing binary types. The only drawback seems to be supporting multiple binary codecs based on backend version, which would probably require a refactor.

    I agree. Regarding the guarantees, this makes me think about the types mapping loading we do. In the beginning, I remember I heard about the possibility of oid changing so I created this dynamic loading. But after all this time I've been working with Npgsql, those oids never changed. :) A lot of times I thought about removing the dynamic loading and use a static one, but as the dynamic was working ok I never went ahead with the refactoring. :) So, I think Postgresql provides a very good guarantee level on internal things, at least somethings like the data types.

    A quick look at NpgsqlTypesHelper shows that the following types don't yet have a binary codec and could benefit from it:

    The date/time/interval types. If this is easy/possible the performance gains should be considerable.
    bit (this is partially what this PR was originally about)
    numeric (may be useless according to @glenebob)
    The "complex/high-level" types (e.g. point/circle/polygon), I agree with @glenebob here that these should be last priority because they're somewhat exotic.
    

    I think the biggest performance gain we can achieve is by optimizing the way we handle those values internally. In the case of bitstring, I know it already has a method which returns the binary string as byte[] which we can use directly. The other ones, as you pointed out, I think should be last priority.

  21. roji commented on Sep 14, 2014

    @roji
    Member

    I agree. Regarding the guarantees, this makes me think about the types mapping loading we do. In the beginning, I remember I heard about the possibility of oid changing so I created this dynamic loading. But after all this time I've been working with Npgsql, those oids never changed. :) A lot of times I thought about removing the dynamic loading and use a static one, but as the dynamic was working ok I never went ahead with the refactoring. :) So, I think Postgresql provides a very good guarantee level on internal things, at least somethings like the data types.

    I tried to search for any statement on guarantees/stability regarding OIDs of Postgresql types and couldn't find any... I also agree that the dynamic loading mechanism has worked out well up to now and so there's probably no reason to change it (hard-coding type OIDs in Npgsql code seems dangerous without any clear guarantee...)

    I think the biggest performance gain we can achieve is by optimizing the way we handle those values internally. In the case of bitstring, I know it already has a method which returns the binary string as byte[] which we can use directly. The other ones, as you pointed out, I think should be last priority.

    Agreed. I think @Emill is taking care of bitstring in this PR, I'll open a separate PR for binary support of date/time types.

    @glenebob, can you confirm that array types over ints and floats are also encoded in binary?

  22. Emill commented on Sep 20, 2014

    @Emill
    ContributorAuthor

    There is a problem when reading a bit[](array of bit-fields) from the db.
    In the current implementation, if a bitstring of length 1 is received, an object of type bool containing the bit is returned instead of a BitString of length 1.
    When a bit[] is returned which contains at least one element with a bitstring of length 1, Npgsql will allocate an array of BitStrings, but the element assignment fails, since a bool can not be converted to a BitString.

    What should be do about this?

  23. Emill commented on Sep 20, 2014

    @Emill
    ContributorAuthor

    Possible solution: what about returning a bool if the type modifier is 1, i.e. the type is explicitly bit(1), and otherwise return a BitString? The same for array types: if it is an array of bit(1), the return type is bool[].

    I think it is strange now, as it returns different datatypes depending on the contents. That is not static-typing...

  24. roji commented on Sep 20, 2014

    @roji
    Member

    @Emill, sounds good to me. BIT should mean .NET bool, BIT(n) should mean .NET BitString...

  25. Emill commented on Sep 20, 2014

    @Emill
    ContributorAuthor

    @franciscojunior When I look at https://github.com/npgsql/Npgsql/blob/a7d29a7a8d6a5d441b96827fe11a3c8d066720eb/Npgsql/NpgsqlParameter.cs#L237, I see that if the value is null, the parameterType the user entered is thrown away and insted String is used. What is the reason for that? If the user later changes the parameter value, it will only accept strings if I understand correctly. Why not simply use the type the user provided?

  26. franciscojunior commented on Oct 17, 2014

    @franciscojunior
    Member

    @franciscojunior When I look at https://github.com/npgsql/Npgsql/blob/a7d29a7a8d6a5d441b96827fe11a3c8d066720eb/Npgsql/NpgsqlParameter.cs#L237, I see that if the value is null, the parameterType the user entered is thrown away and insted String is used. What is the reason for that? If the user later changes the parameter value, it will only accept strings if I understand correctly. Why not simply use the type the user provided?

    Hi, @Emill !
    Sorry for delay to answer.

    Nice catch! I think this isn't correct, it should use the NpgsqlDbType specified by the user.

  27. roji commented on Mar 23, 2015

    @roji
    Member

    Seems like we've fixed this for v3.0...

  28. added theissue type on Jun 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions