Skip to content

Commit 199d33b

Browse files
committed
Perform VACUUM regularly
1 parent b222c61 commit 199d33b

File tree

1 file changed

+51
-1
lines changed

1 file changed

+51
-1
lines changed

src/db/LuaDB.cpp

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,49 @@ int BatchOperation(SQLite::Database& db, const std::unordered_map<std::string, S
112112
return count;
113113
}
114114

115+
void CheckAndVacuum(SQLite::Database& db)
116+
{
117+
bool shouldVacuum = false;
118+
// 查询最后执行时间
119+
{
120+
if (SQLite::Statement query(db, "SELECT value FROM Meta WHERE key = 'last_vacuum_time'"); query.executeStep())
121+
{
122+
time_t lastVacuumTime = 0;
123+
const std::string valueStr = query.getColumn(0).getString();
124+
lastVacuumTime = std::stol(valueStr);
125+
if (const time_t now_t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
126+
now_t - lastVacuumTime > 7 * 24 * 3600)
127+
{
128+
shouldVacuum = true;
129+
}
130+
}
131+
else
132+
{
133+
shouldVacuum = true; // 无记录时触发第一次VACUUM
134+
}
135+
}
136+
137+
// 执行优化逻辑
138+
if (shouldVacuum)
139+
{
140+
try
141+
{
142+
// VACUUM命令不能在事务中执行
143+
db.exec("VACUUM");
144+
// 更新执行时间戳
145+
const time_t now_t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
146+
SQLite::Statement update(db,
147+
"INSERT OR REPLACE INTO Meta (key, value) VALUES ('last_vacuum_time', ?)");
148+
update.bind(1, std::to_string(now_t));
149+
update.exec();
150+
}
151+
catch (const std::exception& e)
152+
{
153+
LogError("VACUUM failed: %s", e.what());
154+
}
155+
}
156+
}
157+
115158
// Database.cpp 优化版本
116159
LuaDB::LuaDB(SSystemGlobalEnvironment* env) :
117160
m_db(std::make_unique<SQLite::Database>("./kcd2db.db", SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE)),
@@ -134,8 +177,13 @@ LuaDB::LuaDB(SSystemGlobalEnvironment* env) :
134177
)
135178
)");
136179
db.exec("CREATE INDEX IF NOT EXISTS idx_store_savefile ON Store(savefile)");
180+
db.exec(R"(
181+
CREATE TABLE IF NOT EXISTS Meta (
182+
key TEXT PRIMARY KEY,
183+
value TEXT
184+
)
185+
)");
137186
});
138-
m_db->exec("VACUUM");
139187
env->pGame->GetIGameFramework()->RegisterListener(this, "LuaDB", FRAMEWORKLISTENERPRIORITY_DEFAULT);
140188
SyncCacheWithDatabase();
141189
#undef SCRIPT_REG_CLASSNAME
@@ -157,6 +205,8 @@ LuaDB::LuaDB(SSystemGlobalEnvironment* env) :
157205

158206
// 工具方法
159207
SCRIPT_REG_TEMPLFUNC(Dump, "");
208+
209+
CheckAndVacuum(*m_db);
160210
}
161211

162212
void LuaDB::SyncCacheWithDatabase()

0 commit comments

Comments
 (0)