我正在尝试将压缩数据插入到sql表中,然后提取并解压缩它。首先,我压缩一个字符串,然后将其插入表(第 1 节)。压缩效果很好。即使当我尝试在插入之前解压缩它时,我也会恢复字符串。插入字符串并稍后尝试将其提取回来后,问题就出现了。
正如您在代码第 2 部分中所看到的。解压已经不起作用了。我不知道为什么它从表中提取后就不再起作用了。
#include <zlc/zlibcomplete.hpp>
#include <string>
#include "3rdparty/sqlite_modern_cpp.h"
using namespace std;
using namespace zlibcomplete;
int main()
{
//SECTION 1
database db("data.db");
db << "CREATE TABLE IF NOT EXISTS paragraph(ID INTEGER PRIMARY KEY, LINE TEXT);";
string line = "hello world!";
//Compress string by using zlib
GZipCompressor compressor(9, auto_flush);
string compressed_line = compressor.compress(line);
compressor.finish();
//IF I DECOMPRESS STRING HERE IT WORKS FINE!!!
GZipDecompressor decompressor;
string output = decompressor.decompress(line);
//insert compressed string into table paragraph
db <<"insert into paragraph(ID,LINE) VALUES (?,?);"
<< 1
<< compressed_line;
//SECTION 2: Problem starts here where I try to return the compressed value
db <<"select line from paragraph where id = ?;"
<< "1"
>>[&](string line)
{
//Decompress string by using zlib
GZipDecompressor decompressor;
string output = decompressor.decompress(line);
//out is empty I don't know why???
cout << output << endl;
};
return 0;
}
#include <zlc/zlibcomplete.hpp>
#include <string>
#include "3rdparty/sqlite_modern_cpp.h"
#include "base64.h"
using namespace std;
using namespace zlibcomplete;
int main()
{
//SECTION 1
database db("data.db");
db << "CREATE TABLE IF NOT EXISTS paragraph(ID INTEGER PRIMARY KEY, LINE TEXT);";
string line = "hello world!";
//Compress string by using zlib
GZipCompressor compressor(9, auto_flush);
string compressed_line = compressor.compress(line);
compressor.finish();
std::string compressed = base64_encode(reinterpret_cast<const unsigned char*>(compressed_line.c_str()), compressed_line.length());
//insert compressed string into table paragraph
db <<"insert into paragraph(ID,LINE) VALUES (?,?);"
<< 1
<< compressed;
db <<"select line from paragraph where id = ?;"
<< "1"
>>[&](string line)
{
//decode HERE
std::string compressed_decoded = base64_decode(line);
//Decompress string by using zlib
GZipDecompressor decompressor;
string output = decompressor.decompress(line);
cout << output << endl;
};
return 0;
}
您的代码无法处理压缩字符串中的零。如果压缩字符串包含字符 0,则文本将被截断并且无法再进行相反操作。
我认为您可以使用替代路径来减少代码(及其维护) - 如果您使用可加载扩展。我最近创建了一个 sqlite-compressions 扩展,它将
gzip
和 brotli
压缩、解压和测试功能添加到 sqlite 作为扩展(或者您可以直接从 Rust 代码中使用它)。加上另一个扩展中的许多哈希函数。
这将允许您使用 SQL 插入和检索原始数据,同时将其存储为 gzip 或 brotli blob:
INSERT INTO table (..., myblob) VALUES (..., gzip(?))
SELECT gzip_decode(myblob) FROM table