How to insert and select images in postgresql - postgresql

Given a JSON file of data to be inserted into a table in Postgresql. One of the fields in the JSON structure is a base64 string. I know there is a data type for psql called BYTEA but how would one insert the base64 string in that field.
I also need to then be able to select the base64 string from the table and display the image in the end.
Note: Bonus points for Golang solutions cause the whole app is in Golang

Related

How do I bulk insert markdown data into Postgres

I am working on Nextjs project. I am trying to insert some JSON data into Postgres database. The data is in markdown and it contains lot of unescaped characters code snippets ``"r"i""n$'t\u0066'` like this. It's not possible to insert that data as a JSON. Is there any way to insert this data?

Convert a BLOB to VARCHAR instead of VARCHAR FOR BIT

I have a BLOB field in a table that I am selecting. This field data consists only of JSON data.
If I do the following:
Select CAST(JSONBLOB as VARCHAR(2000)) from MyTable
--> this returns the value in VARCHAR FOR BIT DATA format.
I just want it as a standard string or varcher - not in bit format.
That is because I need to use JSON2BSON function to convert the JSON to BSON. JSON2BSON accepts a string but it will not accept a VarChar for BIT DATA type...
This conversation should be easy.
I am able to do the select as a VARCHAR FOR BIT DATA.. Manually COPY it using the UI. Paste it into a select literal and convert that to BSON. I need to migrate a bunch of data in this BLOB from JSON to BSON, and doing it manually won't be fast. I just want to explain how simple of a use case this should be.
What is the select command to essentially get this to work:
Select JSON2BSON(CAST(JSONBLOB as VARCHAR(2000))) from MyTable
--> Currently this fails because the CAST converts this (even though its only text characters) to VARCHAR for BIT DATA type and not standard VARCHAR.
What is the suggestion to fix this?
DB2 11 on Windows.
If the data is JSON, then the table column should be CLOB in the first place...
Having the table column a BLOB might make sense if the data is actually already BSON.
You could change the blob into a clob using the converttoclob procedure then you should be ok.
https://www.ibm.com/support/knowledgecenter/SSEPGG_11.5.0/com.ibm.db2.luw.apdv.sqlpl.doc/doc/r0055119.html
You can use this function to remove the "FOR BIT DATA" flag on a column
CREATE OR REPLACE FUNCTION DB_BINARY_TO_CHARACTER(A VARCHAR(32672 OCTETS) FOR BIT DATA)
RETURNS VARCHAR(32672 OCTETS)
NO EXTERNAL ACTION
DETERMINISTIC
BEGIN ATOMIC
RETURN A;
END
or if you are on Db2 11.5 the function SYSIBMADM.UTL_RAW.CAST_TO_VARCHAR2 will also work

Bytea to actual text value in postgresql

I have a table to store file information in postgresql.
select id,filestream,name from Table_file_info
Here filestream is bytea datatype. How to get bytea data into actual text (content of my file) in postgresql.
I tried with below query:
select encode(filestream, 'escape')::text as name from Table_file_info
but i am getting as below
ICAgICAgICAgc2FkZnNhZGZhZCBzZGRkZGRkZGRkIFRlc3R0dA==
actual content of my file is: sadfsadfad sddddddddd Testtt
It looks like base64. Meaning your file was first converted to base64, then converted to bytea (which is kind of pointless since base64 is already text)
select encode(decode(encode(filestream,'escape'),'base64'),'escape') from Table_file_info;

PostgreSQL - How to insert Base64 images strings into a BYTEA column?

I have the following SQL:
CREATE TABLE Documents (
Id INT NOT NULL,
UserId INT NOT NULL,
Label CHARACTER VARYING(220) NOT NULL,
Image BYTEA NOT NULL,
PRIMARY Key(Id),
FOREIGN KEY (UserId) REFERENCES Users(Id)
);
I want to know, How should I have to insert the Base64 image into the table.
The Base64 string comes from a Buffer from after getting the image using the fs module on Node.js.
I'm attempting to insert the image using raw queries of Sequelize, but I have not found proper information on this.
Try this:
insert into table_name (image)
values decode('AcAAFBAO5Az....AQAAAFBCO5gT/AEAABT', 'base64')
Here is some information about decode
https://www.base64decode.net/postgresql-decode
To answer the question regarding Postgres and Sequelize:
You will need to use the Sequelize.BLOB('tiny') datatype to model a BYTEA Postgres datatype.
Here is more information about datatypes in Sequelize (it also contains the above information):
http://docs.sequelizejs.com/manual/data-types.html
When converting into a tiny blob, Postgres will default to utf-8, meaning you'll probably want to turn your data into a utf-8 encoding, store the data, and the read it as utf-8.
EDIT:
You will use Base64 to encode the image binary data into an ASCII string:
https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding

How to insert (raw bytes from file data) using a plain text script

Database: Postgres 9.1
I have a table called logos defined like this:
create type image_type as enum ('png');
create table logos (
id UUID primary key,
bytes bytea not null,
type image_type not null,
created timestamp with time zone default current_timestamp not null
);
create index logo_id_idx on logos(id);
I want to be able to insert records into this table in 2 ways.
The first (and most common) way rows will be inserted in the table will be that a user will provide a PNG image file via an html file upload form. The code processing the request on the server will receive a byte array containing the data in the PNG image file and insert a record in the table using something very similar to what is explained here. There are plenty of example of how to insert byte arrays into a postgresql field of type bytea on the internet. This is an easy exercise. An example of the insert code would look like this:
insert into logos (id, bytes, type, created) values (?, ?, ?, now())
And the bytes would be set with something like:
...
byte[] bytes = ... // read PNG file into a byte array.
...
ps.setBytes(2, bytes);
...
The second way rows will be inserted in the table will be from a plain text file script. The reason this is needed is only to populate test data into the table for automated tests, or to initialize the database with a few records for a remote development environment.
Regardless of how the data is entered in the table, the application will obviously need to be able to select the bytea data from the table and convert it back into a PNG image.
Question
How does one properly encode a byte array, to be able to insert the data from within a script, in such a way that only the original bytes contained in the file are stored in the database?
I can write code to read the file and spit out insert statements to populate the script. But I don't know how to encode the byte array for the plain text script such that when running the script from psql the image data will be the same as if the file was inserted using the setBytes jdbc code.
I would like to run the script with something like this:
psql -U username -d dataBase -a -f test_data.sql
The easiest way, IMO, to represent bytea data in an SQL file is to use the hex format:
8.4.1. bytea Hex Format
The "hex" format encodes binary data as 2 hexadecimal digits per byte, most significant nibble first. The entire string is preceded by the sequence \x (to distinguish it from the escape format). In some contexts, the initial backslash may need to be escaped by doubling it, in the same cases in which backslashes have to be doubled in escape format; details appear below. The hexadecimal digits can be either upper or lower case, and whitespace is permitted between digit pairs (but not within a digit pair nor in the starting \x sequence). The hex format is compatible with a wide range of external applications and protocols, and it tends to be faster to convert than the escape format, so its use is preferred.
Example:
SELECT E'\\xDEADBEEF';
Converting an array of bytes to hex should be trivial in any language that a sane person (such a yourself) would use to write the SQL file generator.