I'm trying to save binary data into postgres. Parts of the code is shown below:
string readFile2(const string &fileName)
{
ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);
ifs.seekg(0, ios::end);
ifstream::pos_type fileSize = ifs.tellg();
ifs.seekg(0, ios::beg);
vector<char> bytes(fileSize);
ifs.read(bytes.data(), fileSize);
cout.write(bytes.data(),bytes.size());
cout << "\n";
cout << fileSize;
cout << "\n";
// return bytes.data();
return string(bytes.data(), fileSize);
}
int main() {
string content;
string test = "h";
char test1 = 'C';
try {
cout << "A1 \n";;
content = readFile2("/var/opt/lizardfs/lib/lizardfs/metadata.mfs");
pqxx::connection c("postgresql://mark@localhost:26257/metadata");
pqxx::nontransaction w(c);
w.exec("CREATE TABLE IF NOT EXISTS binary (id INT PRIMARY KEY, meta BLOB)");
w.exec("INSERT INTO binary (id,meta) VALUES (18, '"+content+"')");
}
The problem is that if I try to run the code I get the error:
ERROR: lexical error: unterminated string
DETAIL: source SQL:
INSERT INTO binary (id,meta) VALUES (18, 'LIZM 2.9
I think that is because the next character is a null character. Hexdump shows 00
If instead of having the readFile2 function return return string(bytes.data(), fileSize); and returns return bytes.data(); then the error disappears. However, going into the database all I can see is the first few bytes of the binary file, shown below:
id | meta
-----+-----------
15 | LIZM 2.9
I'm not sure why it's not able to store all the binary content when I have return bytes.data();. How do I get the entire content of the binary file to save in the database?