Thread: type cast about int to bit
hi,
there is a problem about type cast that i don't understand, follow is my test.
postgres=# select 10::bit(3);
bit
-----
010
(1 row)
bit
-----
010
(1 row)
postgres=# select 10::bit varying(3);
ERROR: cannot cast type integer to bit varying
LINE 1: select 10::bit varying(3);
^
postgres=#
ERROR: cannot cast type integer to bit varying
LINE 1: select 10::bit varying(3);
^
postgres=#
my question is why int can cast to bit , i want to know the reason.
thank you for your timing.
does the mailing list mangle these, or is it just GMANE? On 2012-02-06, zoulx1982 <zoulx1982@163.com> wrote: >hi, >there is a problem about type cast that i don't understand, follow is my test. > >postgres=# select 10::bit(3); > bit >----- > 010 >(1 row) >postgres=# select 10::bit varying(3); >ERROR: cannot cast type integer to bit varying >LINE 1: select 10::bit varying(3); > ^ >postgres=# > >my question is why int can cast to bit , i want to know the reason. >thank you for your timing. possibly postgres doesn't know what size to make the result. -- ⚂⚃ 100% natural
On Sunday, February 05, 2012 10:11:12 pm zoulx1982 wrote: > hi, > there is a problem about type cast that i don't understand, follow is my > test. > > postgres=# select 10::bit(3); > bit > ----- > 010 > (1 row) > postgres=# select 10::bit varying(3); > ERROR: cannot cast type integer to bit varying > LINE 1: select 10::bit varying(3); > ^ > postgres=# > > my question is why int can cast to bit , i want to know the reason. > thank you for your timing. My guess it depends on the fact that bit types are stored as either char or varchar depending on whether they are bit or bit varying. In the first case you are basically doing an int-->char, for which there is a built in cast. In the second case you are doing int-->varchar for which there is not a cast. -- Adrian Klaver adrian.klaver@gmail.com
On Monday, February 06, 2012 6:42:45 pm zoulx1982 wrote: > you mean there is no cast function for int to varchar ? > i see sure it is. > That is why I said my guess:) If you want to see what is actually going on take a look at: http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/adt/varbit.c;h=adb08369ed28ab6b52aa2cd5213bcd5b4d8de7ad;hb=HEAD The ERROR though is coming further up, in the parser , if I am following correctly. This because as you have found out there is no direct cast from integer to varbit. Why that is for someone else to answer, as I don't know. Though a little playing around got this, not pretty but it seems to work: test(5432)aklaver=>SELECT 10::bit(3)::varbit(3);varbit --------010 (1 row) test(5432)aklaver=>SELECT 10::bit(3)::varbit(4);varbit --------010 (1 row) test(5432)aklaver=>SELECT 10::bit(4)::varbit(4);varbit --------1010 (1 row) test(5432)aklaver=>SELECT 10::bit(4)::varbit(3);varbit --------101 -- Adrian Klaver adrian.klaver@gmail.com