@@ -33,9 +33,14 @@ static sqlite3 *get_handle(std::unique_ptr<void, std::function<void(void *)>> &h
3333 return static_cast <sqlite3 *>(handle.get ());
3434}
3535
36+ template <bool IsWriter>
3637static void close_handle (void *handle)
3738{
3839 sqlite3 *db = static_cast <sqlite3 *>(handle);
40+ if (IsWriter)
41+ {
42+ sqlite3_exec (db, " VACUUM;" , nullptr , nullptr , nullptr );
43+ }
3944 sqlite3_close (db);
4045}
4146
@@ -100,7 +105,7 @@ class stored_page : public hyperpage::page
100105 size_t _length;
101106};
102107
103- hyperpage::reader::reader (const std::string &db_path) : _handle(nullptr , close_handle)
108+ hyperpage::reader::reader (const std::string &db_path) : _handle(nullptr , close_handle< false > )
104109{
105110 sqlite3 *db = nullptr ;
106111 if (!sqlite_call (SQLITE_OK , sqlite3_open, db_path.c_str (), &db))
@@ -121,7 +126,7 @@ std::unique_ptr<hyperpage::page> hyperpage::reader::load(const std::string &page
121126 return result;
122127}
123128
124- hyperpage::writer::writer (const std::string &db_path) : _handle(nullptr , close_handle)
129+ hyperpage::writer::writer (const std::string &db_path) : _handle(nullptr , close_handle< true > )
125130{
126131 sqlite3 *db = nullptr ;
127132 if (!sqlite_call (SQLITE_OK , sqlite3_open, db_path.c_str (), &db))
@@ -133,15 +138,17 @@ hyperpage::writer::writer(const std::string &db_path) : _handle(nullptr, close_h
133138 " path TEXT PRIMARY KEY, "
134139 " mime_type TEXT, "
135140 " content BLOB);"
136- " CREATE INDEX IF NOT EXISTS path_index ON hyperpage (path);" ;
141+ " CREATE UNIQUE INDEX IF NOT EXISTS path_index ON hyperpage (path);" ;
137142 sqlite3_exec (db, create_table_query.c_str (), nullptr , nullptr , nullptr );
138143 _handle.reset (db);
139144}
140145
141146void hyperpage::writer::store (const hyperpage::page &page)
142147{
143148 sqlite3 *db = get_handle (_handle);
144- const std::string query = " INSERT OR REPLACE INTO hyperpage (path, mime_type, content) VALUES (?, ?, ?);" ;
149+ const std::string query =
150+ " INSERT INTO hyperpage (path, mime_type, content) VALUES (?, ?, ?);"
151+ " ON CONFLICT(path) DO UPDATE SET mime_type=excluded.mime_type, content=excluded.content;" ;
145152 sqlite3_stmt *stmt = nullptr ;
146153
147154 sqlite3_prepare_v2 (db, query.c_str (), -1 , &stmt, nullptr );
@@ -154,5 +161,6 @@ void hyperpage::writer::store(const hyperpage::page &page)
154161
155162std::string hyperpage::mime_type (const std::string &path)
156163{
157- return std::string (getMegaMimeType (path.c_str ()));
164+ const char *mime = getMegaMimeType (path.c_str ());
165+ return std::string (mime ? mime : " application/octet-stream" );
158166}
0 commit comments