Can I treat Varbinary and bytea fields equivalently?
-
24-02-2021 - |
سؤال
I moved a mysql DB to Postgres, but some of the tables had a varbinary(16)
field (to store an ip address).
Postgres does not support varbinary
fields, and after some research, I found that the Postgres equivalent is bytea
.
So, I went ahead and made tables with bytea
as the field type for the ip columns.
Now, I am not sure, but this might be causing me problems.
So, now my question is if bytea
and varbinary
can be treated totally equally or not.
For example, if the original MySQL query is:
INSERT INTO messages(userID, userName, userRole, dateTime, ip, text)
Values('21212111','bot','4',NOW(), inet_pton($ip), 'hi');
Note: I included some php in there, because my logs don't show what the inserted ip address is (It's a blob/something)
Now, would this query store the exact same data if it was a bytea
field instead? I would presume yes, but does the same hold true for a select statement?
i.e. Would, this query return the same data regardless of whether the ip field was varbinary
or bytea
?
SELECT userID, userName, userRole, channel ,ip FROM table
Thanks for your time, have a good day.
المحلول
Yes, bytea
is an equivalent to varbinary
/image
/blob
et al. Having said that, PostgreSQL does come with an inet
type as standard, which will take an IPv4 address in textual representation and store it as a 32-bit integer.
نصائح أخرى
IIRC, you have to use pg_escape_bytea()
and pg_unescape_bytea()
functions.
Postgres does not support varbinary fields, and after some research, I found that the Postgres equivalent is bytea.
So, I went ahead and made tables with bytea as the field type for the ip columns.
INET is made for ip-addresses, IPv4 and IPv6, bytea is made for binary data. Always use the best matching datatype, PostgreSQL has many great datatypes. And you can create your own datatypes (TYPE or DOMAIN), if you want to. But never abuse bytea just because you can.