Skip to content

Commit 750f3e1

Browse files
1oca1h0stMecozea
authored andcommitted
fix: 解决SQLITE删除数据limit报错的问题,默认情况下SQLITE不支持DELETE里面的LIMIT
1 parent 6d65ce4 commit 750f3e1

File tree

1 file changed

+28
-23
lines changed

1 file changed

+28
-23
lines changed

internal/dashboard/cleanup_service.go

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -126,10 +126,14 @@ func (s *CleanupService) cleanupSSEData() CleanupResult {
126126

127127
for {
128128
var deletedCount int64
129+
// SQLite 不支持 DELETE ... LIMIT,使用子查询方式
129130
err := s.db.Exec(`
130-
DELETE FROM endpoint_sse
131-
WHERE event_time < ?
132-
LIMIT ?
131+
DELETE FROM endpoint_sse
132+
WHERE id IN (
133+
SELECT id FROM endpoint_sse
134+
WHERE event_time < ?
135+
LIMIT ?
136+
)
133137
`, cutoffTime, batchSize).Error
134138

135139
if err != nil {
@@ -173,10 +177,14 @@ func (s *CleanupService) cleanupSummaryData() CleanupResult {
173177

174178
for {
175179
var deletedCount int64
180+
// SQLite 不支持 DELETE ... LIMIT,使用子查询方式
176181
err := s.db.Exec(`
177-
DELETE FROM traffic_hourly_summary
178-
WHERE hour_time < ?
179-
LIMIT ?
182+
DELETE FROM traffic_hourly_summary
183+
WHERE id IN (
184+
SELECT id FROM traffic_hourly_summary
185+
WHERE hour_time < ?
186+
LIMIT ?
187+
)
180188
`, cutoffTime, batchSize).Error
181189

182190
if err != nil {
@@ -217,10 +225,14 @@ func (s *CleanupService) cleanupOperationLogs() CleanupResult {
217225

218226
for {
219227
var deletedCount int64
228+
// SQLite 不支持 DELETE ... LIMIT,使用子查询方式
220229
err := s.db.Exec(`
221-
DELETE FROM tunnel_operation_logs
222-
WHERE created_at < ?
223-
LIMIT ?
230+
DELETE FROM tunnel_operation_logs
231+
WHERE id IN (
232+
SELECT id FROM tunnel_operation_logs
233+
WHERE created_at < ?
234+
LIMIT ?
235+
)
224236
`, cutoffTime, batchSize).Error
225237

226238
if err != nil {
@@ -252,20 +264,13 @@ func (s *CleanupService) optimizeTables() CleanupResult {
252264
Duration: 0,
253265
}
254266

255-
tables := []string{
256-
"endpoint_sse",
257-
"traffic_hourly_summary",
258-
"tunnel_operation_logs",
259-
"tunnels",
260-
"endpoints",
261-
}
262-
263-
for _, table := range tables {
264-
// MySQL的OPTIMIZE TABLE命令
265-
if err := s.db.Exec(fmt.Sprintf("OPTIMIZE TABLE %s", table)).Error; err != nil {
266-
// 如果优化失败,记录错误但继续处理其他表
267-
log.Printf("[数据清理] 优化表 %s 失败: %v", table, err)
268-
}
267+
// SQLite 使用 VACUUM 命令来优化数据库
268+
// VACUUM 会重建整个数据库文件,回收未使用的空间
269+
if err := s.db.Exec("VACUUM").Error; err != nil {
270+
log.Printf("[数据清理] VACUUM 优化失败: %v", err)
271+
result.Error = fmt.Errorf("VACUUM 优化失败: %v", err)
272+
} else {
273+
log.Println("[数据清理] VACUUM 优化成功")
269274
}
270275

271276
result.Duration = time.Since(start)

0 commit comments

Comments
 (0)