ErisPulse 1.1.12__py3-none-any.whl → 1.1.14__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ErisPulse/db.py CHANGED
@@ -1,12 +1,475 @@
1
+ """
2
+ # 环境配置
3
+
4
+ 提供键值存储、事务支持、快照和恢复功能,用于管理框架配置数据。基于SQLite实现持久化存储,支持复杂数据类型和原子操作。
5
+
6
+ ## 核心功能
7
+ 1. 键值存储
8
+ 2. 事务支持
9
+ 3. 数据库快照
10
+ 4. 自动备份
11
+ 5. 配置文件集成
12
+
13
+ ## API 文档
14
+
15
+ ### 基本操作
16
+ #### get(key: str, default: Any = None) -> Any
17
+ 获取配置项的值。
18
+ - 参数:
19
+ - key: 配置项键名
20
+ - default: 如果键不存在时返回的默认值
21
+ - 返回:
22
+ - Any: 配置项的值,如果是JSON格式则自动解析为Python对象
23
+ - 示例:
24
+ ```python
25
+ # 获取基本配置
26
+ timeout = sdk.env.get("network.timeout", 30)
27
+
28
+ # 获取结构化数据
29
+ user_settings = sdk.env.get("user.settings", {})
30
+ if "theme" in user_settings:
31
+ apply_theme(user_settings["theme"])
32
+
33
+ # 条件获取
34
+ debug_mode = sdk.env.get("app.debug", False)
35
+ if debug_mode:
36
+ enable_debug_features()
37
+ ```
38
+
39
+ #### set(key: str, value: Any) -> bool
40
+ 设置配置项的值。
41
+ - 参数:
42
+ - key: 配置项键名
43
+ - value: 配置项的值,复杂类型会自动序列化为JSON
44
+ - 返回:
45
+ - bool: 操作是否成功
46
+ - 示例:
47
+ ```python
48
+ # 设置基本配置
49
+ sdk.env.set("app.name", "MyApplication")
50
+
51
+ # 设置结构化数据
52
+ sdk.env.set("server.config", {
53
+ "host": "localhost",
54
+ "port": 8080,
55
+ "workers": 4
56
+ })
57
+
58
+ # 更新现有配置
59
+ current_settings = sdk.env.get("user.settings", {})
60
+ current_settings["last_login"] = datetime.now().isoformat()
61
+ sdk.env.set("user.settings", current_settings)
62
+ ```
63
+
64
+ #### delete(key: str) -> bool
65
+ 删除配置项。
66
+ - 参数:
67
+ - key: 要删除的配置项键名
68
+ - 返回:
69
+ - bool: 操作是否成功
70
+ - 示例:
71
+ ```python
72
+ # 删除临时配置
73
+ sdk.env.delete("temp.session")
74
+
75
+ # 条件删除
76
+ if not is_feature_enabled():
77
+ sdk.env.delete("feature.config")
78
+
79
+ # 清理旧配置
80
+ for key in sdk.env.get_all_keys():
81
+ if key.startswith("deprecated."):
82
+ sdk.env.delete(key)
83
+ ```
84
+
85
+ #### get_all_keys() -> list[str]
86
+ 获取所有配置项的键名。
87
+ - 参数: 无
88
+ - 返回:
89
+ - list[str]: 所有配置项的键名列表
90
+ - 示例:
91
+ ```python
92
+ # 列出所有配置
93
+ all_keys = sdk.env.get_all_keys()
94
+ print(f"当前有 {len(all_keys)} 个配置项")
95
+
96
+ # 按前缀过滤
97
+ user_keys = [k for k in sdk.env.get_all_keys() if k.startswith("user.")]
98
+ print(f"用户相关配置: {user_keys}")
99
+
100
+ # 导出配置摘要
101
+ config_summary = {}
102
+ for key in sdk.env.get_all_keys():
103
+ parts = key.split(".")
104
+ if len(parts) > 1:
105
+ category = parts[0]
106
+ if category not in config_summary:
107
+ config_summary[category] = 0
108
+ config_summary[category] += 1
109
+ print("配置分类统计:", config_summary)
110
+ ```
111
+
112
+ ### 批量操作
113
+ #### get_multi(keys: list) -> dict
114
+ 批量获取多个配置项的值。
115
+ - 参数:
116
+ - keys: 要获取的配置项键名列表
117
+ - 返回:
118
+ - dict: 键值对字典,只包含存在的键
119
+ - 示例:
120
+ ```python
121
+ # 批量获取配置
122
+ settings = sdk.env.get_multi([
123
+ "app.name",
124
+ "app.version",
125
+ "app.debug"
126
+ ])
127
+ print(f"应用: {settings.get('app.name')} v{settings.get('app.version')}")
128
+
129
+ # 获取相关配置组
130
+ db_keys = ["database.host", "database.port", "database.user", "database.password"]
131
+ db_config = sdk.env.get_multi(db_keys)
132
+ connection = create_db_connection(**db_config)
133
+
134
+ # 配置存在性检查
135
+ required_keys = ["api.key", "api.endpoint", "api.version"]
136
+ config = sdk.env.get_multi(required_keys)
137
+ missing = [k for k in required_keys if k not in config]
138
+ if missing:
139
+ raise ValueError(f"缺少必要配置: {missing}")
140
+ ```
141
+
142
+ #### set_multi(items: dict) -> bool
143
+ 批量设置多个配置项的值。
144
+ - 参数:
145
+ - items: 要设置的键值对字典
146
+ - 返回:
147
+ - bool: 操作是否成功
148
+ - 示例:
149
+ ```python
150
+ # 批量设置基本配置
151
+ sdk.env.set_multi({
152
+ "app.name": "MyApp",
153
+ "app.version": "1.0.0",
154
+ "app.debug": True
155
+ })
156
+
157
+ # 更新系统设置
158
+ sdk.env.set_multi({
159
+ "system.max_connections": 100,
160
+ "system.timeout": 30,
161
+ "system.retry_count": 3
162
+ })
163
+
164
+ # 从外部配置导入
165
+ import json
166
+ with open("config.json", "r") as f:
167
+ external_config = json.load(f)
168
+
169
+ # 转换为扁平结构
170
+ flat_config = {}
171
+ for section, values in external_config.items():
172
+ for key, value in values.items():
173
+ flat_config[f"{section}.{key}"] = value
174
+
175
+ sdk.env.set_multi(flat_config)
176
+ ```
177
+
178
+ #### delete_multi(keys: list) -> bool
179
+ 批量删除多个配置项。
180
+ - 参数:
181
+ - keys: 要删除的配置项键名列表
182
+ - 返回:
183
+ - bool: 操作是否成功
184
+ - 示例:
185
+ ```python
186
+ # 批量删除临时配置
187
+ temp_keys = [k for k in sdk.env.get_all_keys() if k.startswith("temp.")]
188
+ sdk.env.delete_multi(temp_keys)
189
+
190
+ # 删除特定模块的所有配置
191
+ module_keys = [k for k in sdk.env.get_all_keys() if k.startswith("module_name.")]
192
+ sdk.env.delete_multi(module_keys)
193
+
194
+ # 清理测试数据
195
+ test_keys = ["test.user", "test.data", "test.results"]
196
+ sdk.env.delete_multi(test_keys)
197
+ ```
198
+
199
+ ### 事务管理
200
+ #### transaction() -> contextmanager
201
+ 创建事务上下文,确保多个操作的原子性。
202
+ - 参数: 无
203
+ - 返回:
204
+ - contextmanager: 事务上下文管理器
205
+ - 示例:
206
+ ```python
207
+ # 基本事务
208
+ with sdk.env.transaction():
209
+ sdk.env.set("user.id", user_id)
210
+ sdk.env.set("user.name", user_name)
211
+ sdk.env.set("user.email", user_email)
212
+
213
+ # 带有条件检查的事务
214
+ def update_user_safely(user_id, new_data):
215
+ with sdk.env.transaction():
216
+ current = sdk.env.get(f"user.{user_id}", None)
217
+ if not current:
218
+ return False
219
+
220
+ for key, value in new_data.items():
221
+ sdk.env.set(f"user.{user_id}.{key}", value)
222
+
223
+ sdk.env.set(f"user.{user_id}.updated_at", time.time())
224
+ return True
225
+
226
+ # 复杂业务逻辑事务
227
+ def transfer_credits(from_user, to_user, amount):
228
+ with sdk.env.transaction():
229
+ # 检查余额
230
+ from_balance = sdk.env.get(f"user.{from_user}.credits", 0)
231
+ if from_balance < amount:
232
+ raise ValueError("余额不足")
233
+
234
+ # 更新余额
235
+ sdk.env.set(f"user.{from_user}.credits", from_balance - amount)
236
+
237
+ to_balance = sdk.env.get(f"user.{to_user}.credits", 0)
238
+ sdk.env.set(f"user.{to_user}.credits", to_balance + amount)
239
+
240
+ # 记录交易
241
+ transaction_id = str(uuid.uuid4())
242
+ sdk.env.set(f"transaction.{transaction_id}", {
243
+ "from": from_user,
244
+ "to": to_user,
245
+ "amount": amount,
246
+ "timestamp": time.time()
247
+ })
248
+ ```
249
+
250
+ ### 快照管理
251
+ #### snapshot(name: str = None) -> str
252
+ 创建数据库快照。
253
+ - 参数:
254
+ - name: 快照名称,默认使用当前时间戳
255
+ - 返回:
256
+ - str: 快照文件路径
257
+ - 示例:
258
+ ```python
259
+ # 创建命名快照
260
+ sdk.env.snapshot("before_migration")
261
+
262
+ # 创建定期备份
263
+ def create_daily_backup():
264
+ date_str = datetime.now().strftime("%Y%m%d")
265
+ return sdk.env.snapshot(f"daily_{date_str}")
266
+
267
+ # 在重要操作前创建快照
268
+ def safe_operation():
269
+ snapshot_path = sdk.env.snapshot("pre_operation")
270
+ try:
271
+ perform_risky_operation()
272
+ except Exception as e:
273
+ sdk.logger.error(f"操作失败: {e}")
274
+ sdk.env.restore(snapshot_path)
275
+ return False
276
+ return True
277
+ ```
278
+
279
+ #### restore(snapshot_name: str) -> bool
280
+ 从快照恢复数据库。
281
+ - 参数:
282
+ - snapshot_name: 快照名称或路径
283
+ - 返回:
284
+ - bool: 恢复是否成功
285
+ - 示例:
286
+ ```python
287
+ # 恢复到指定快照
288
+ success = sdk.env.restore("before_migration")
289
+ if success:
290
+ print("成功恢复到之前的状态")
291
+ else:
292
+ print("恢复失败")
293
+
294
+ # 回滚到最近的每日备份
295
+ def rollback_to_last_daily():
296
+ snapshots = sdk.env.list_snapshots()
297
+ daily_snapshots = [s for s in snapshots if s[0].startswith("daily_")]
298
+ if daily_snapshots:
299
+ latest = daily_snapshots[0] # 列表已按时间排序
300
+ return sdk.env.restore(latest[0])
301
+ return False
302
+
303
+ # 灾难恢复
304
+ def disaster_recovery():
305
+ snapshots = sdk.env.list_snapshots()
306
+ if not snapshots:
307
+ print("没有可用的快照")
308
+ return False
309
+
310
+ print("可用快照:")
311
+ for i, (name, date, size) in enumerate(snapshots):
312
+ print(f"{i+1}. {name} - {date} ({size/1024:.1f} KB)")
313
+
314
+ choice = input("选择要恢复的快照编号: ")
315
+ try:
316
+ index = int(choice) - 1
317
+ if 0 <= index < len(snapshots):
318
+ return sdk.env.restore(snapshots[index][0])
319
+ except ValueError:
320
+ pass
321
+ return False
322
+ ```
323
+
324
+ #### list_snapshots() -> list
325
+ 列出所有可用的快照。
326
+ - 参数: 无
327
+ - 返回:
328
+ - list: 快照信息列表,每项包含(名称, 创建时间, 大小)
329
+ - 示例:
330
+ ```python
331
+ # 列出所有快照
332
+ snapshots = sdk.env.list_snapshots()
333
+ print(f"共有 {len(snapshots)} 个快照")
334
+
335
+ # 显示快照详情
336
+ for name, date, size in snapshots:
337
+ print(f"名称: {name}")
338
+ print(f"创建时间: {date}")
339
+ print(f"大小: {size/1024:.2f} KB")
340
+ print("-" * 30)
341
+
342
+ # 查找特定快照
343
+ def find_snapshot(prefix):
344
+ snapshots = sdk.env.list_snapshots()
345
+ return [s for s in snapshots if s[0].startswith(prefix)]
346
+ ```
347
+
348
+ #### delete_snapshot(name: str) -> bool
349
+ 删除指定的快照。
350
+ - 参数:
351
+ - name: 要删除的快照名称
352
+ - 返回:
353
+ - bool: 删除是否成功
354
+ - 示例:
355
+ ```python
356
+ # 删除指定快照
357
+ sdk.env.delete_snapshot("old_backup")
358
+
359
+ # 清理过期快照
360
+ def cleanup_old_snapshots(days=30):
361
+ snapshots = sdk.env.list_snapshots()
362
+ cutoff = datetime.now() - timedelta(days=days)
363
+ for name, date, _ in snapshots:
364
+ if date < cutoff:
365
+ sdk.env.delete_snapshot(name)
366
+ print(f"已删除过期快照: {name}")
367
+
368
+ # 保留最新的N个快照
369
+ def retain_latest_snapshots(count=5):
370
+ snapshots = sdk.env.list_snapshots()
371
+ if len(snapshots) > count:
372
+ for name, _, _ in snapshots[count:]:
373
+ sdk.env.delete_snapshot(name)
374
+ ```
375
+
376
+ ## 最佳实践
377
+
378
+ 1. 配置组织
379
+ ```python
380
+ # 使用层次结构组织配置
381
+ sdk.env.set("app.server.host", "localhost")
382
+ sdk.env.set("app.server.port", 8080)
383
+ sdk.env.set("app.database.url", "postgresql://localhost/mydb")
384
+
385
+ # 使用命名空间避免冲突
386
+ sdk.env.set("module1.config.timeout", 30)
387
+ sdk.env.set("module2.config.timeout", 60)
388
+ ```
389
+
390
+ 2. 事务使用
391
+ ```python
392
+ # 确保数据一致性
393
+ def update_configuration(config_data):
394
+ with sdk.env.transaction():
395
+ # 验证
396
+ for key, value in config_data.items():
397
+ if not validate_config(key, value):
398
+ raise ValueError(f"无效的配置: {key}")
399
+
400
+ # 更新
401
+ for key, value in config_data.items():
402
+ sdk.env.set(key, value)
403
+
404
+ # 记录更新
405
+ sdk.env.set("config.last_updated", time.time())
406
+ ```
407
+
408
+ 3. 快照管理
409
+ ```python
410
+ # 定期创建快照
411
+ def schedule_backups():
412
+ # 每日快照
413
+ if not sdk.env.snapshot(f"daily_{datetime.now().strftime('%Y%m%d')}"):
414
+ sdk.logger.error("每日快照创建失败")
415
+
416
+ # 清理旧快照
417
+ cleanup_old_snapshots(days=30)
418
+
419
+ # 自动备份重要操作
420
+ def safe_bulk_update(updates):
421
+ snapshot_name = f"pre_update_{time.time()}"
422
+ sdk.env.snapshot(snapshot_name)
423
+
424
+ try:
425
+ with sdk.env.transaction():
426
+ for key, value in updates.items():
427
+ sdk.env.set(key, value)
428
+ except Exception as e:
429
+ sdk.logger.error(f"批量更新失败: {e}")
430
+ sdk.env.restore(snapshot_name)
431
+ raise
432
+ ```
433
+
434
+ ## 注意事项
435
+
436
+ 1. 性能优化
437
+ - 使用批量操作代替多次单独操作
438
+ - 合理使用事务减少数据库操作次数
439
+ - 避免存储过大的值,考虑分片存储
440
+
441
+ 2. 数据安全
442
+ - 定期创建快照备份重要数据
443
+ - 使用事务确保数据一致性
444
+ - 不要存储敏感信息(如密码)的明文
445
+
446
+ 3. 配置管理
447
+ - 使用有意义的键名和层次结构
448
+ - 记录配置的更新历史
449
+ - 定期清理不再使用的配置
450
+
451
+ 4. 错误处理
452
+ - 所有数据库操作都应该有错误处理
453
+ - 重要操作前创建快照以便回滚
454
+ - 记录所有关键操作的日志
455
+ """
456
+
1
457
  import os
2
458
  import json
3
459
  import sqlite3
4
460
  import importlib.util
461
+ import shutil
462
+ import time
463
+ import threading
5
464
  from pathlib import Path
465
+ from datetime import datetime
466
+ from functools import lru_cache
467
+ from .raiserr import raiserr
6
468
 
7
469
  class EnvManager:
8
470
  _instance = None
9
471
  db_path = os.path.join(os.path.dirname(__file__), "config.db")
472
+ SNAPSHOT_DIR = os.path.join(os.path.dirname(__file__), "snapshots")
10
473
 
11
474
  def __new__(cls, *args, **kwargs):
12
475
  if not cls._instance:
@@ -15,12 +478,21 @@ class EnvManager:
15
478
 
16
479
  def __init__(self):
17
480
  if not hasattr(self, "_initialized"):
481
+ # 确保关键属性在初始化时都有默认值
482
+ self._last_snapshot_time = time.time()
483
+ self._snapshot_interval = 3600
18
484
  self._init_db()
19
485
  self._initialized = True
20
486
 
21
487
  def _init_db(self):
22
488
  os.makedirs(os.path.dirname(self.db_path), exist_ok=True)
489
+ os.makedirs(self.SNAPSHOT_DIR, exist_ok=True)
23
490
  conn = sqlite3.connect(self.db_path)
491
+
492
+ # 启用WAL模式提高并发性能
493
+ conn.execute("PRAGMA journal_mode=WAL")
494
+ conn.execute("PRAGMA synchronous=NORMAL")
495
+
24
496
  cursor = conn.cursor()
25
497
  cursor.execute("""
26
498
  CREATE TABLE IF NOT EXISTS config (
@@ -30,6 +502,10 @@ class EnvManager:
30
502
  """)
31
503
  conn.commit()
32
504
  conn.close()
505
+
506
+ # 初始化自动快照调度器
507
+ self._last_snapshot_time = time.time() # 初始化为当前时间
508
+ self._snapshot_interval = 3600 # 默认每小时自动快照
33
509
 
34
510
  def get(self, key, default=None):
35
511
  try:
@@ -59,18 +535,128 @@ class EnvManager:
59
535
 
60
536
  def set(self, key, value):
61
537
  serialized_value = json.dumps(value) if isinstance(value, (dict, list)) else str(value)
62
- conn = sqlite3.connect(self.db_path)
63
- cursor = conn.cursor()
64
- cursor.execute("INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)", (key, serialized_value))
65
- conn.commit()
66
- conn.close()
538
+ with self.transaction():
539
+ conn = sqlite3.connect(self.db_path)
540
+ cursor = conn.cursor()
541
+ cursor.execute("INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)", (key, serialized_value))
542
+ conn.commit()
543
+ conn.close()
544
+
545
+ self._check_auto_snapshot()
546
+ return True
547
+
548
+ def set_multi(self, items):
549
+ with self.transaction():
550
+ conn = sqlite3.connect(self.db_path)
551
+ cursor = conn.cursor()
552
+ for key, value in items.items():
553
+ serialized_value = json.dumps(value) if isinstance(value, (dict, list)) else str(value)
554
+ cursor.execute("INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)",
555
+ (key, serialized_value))
556
+ conn.commit()
557
+ conn.close()
558
+
559
+ self._check_auto_snapshot()
560
+ return True
67
561
 
68
562
  def delete(self, key):
563
+ with self.transaction():
564
+ conn = sqlite3.connect(self.db_path)
565
+ cursor = conn.cursor()
566
+ cursor.execute("DELETE FROM config WHERE key = ?", (key,))
567
+ conn.commit()
568
+ conn.close()
569
+
570
+ self._check_auto_snapshot()
571
+ return True
572
+
573
+ def delete_multi(self, keys):
574
+ with self.transaction():
575
+ conn = sqlite3.connect(self.db_path)
576
+ cursor = conn.cursor()
577
+ cursor.executemany("DELETE FROM config WHERE key = ?", [(k,) for k in keys])
578
+ conn.commit()
579
+ conn.close()
580
+
581
+ self._check_auto_snapshot()
582
+ return True
583
+
584
+ def get_multi(self, keys):
69
585
  conn = sqlite3.connect(self.db_path)
70
586
  cursor = conn.cursor()
71
- cursor.execute("DELETE FROM config WHERE key = ?", (key,))
72
- conn.commit()
587
+ placeholders = ','.join(['?'] * len(keys))
588
+ cursor.execute(f"SELECT key, value FROM config WHERE key IN ({placeholders})", keys)
589
+ results = {row[0]: json.loads(row[1]) if row[1].startswith(('{', '[')) else row[1]
590
+ for row in cursor.fetchall()}
73
591
  conn.close()
592
+ return results
593
+
594
+ def transaction(self):
595
+ return self._Transaction(self)
596
+
597
+ class _Transaction:
598
+ def __init__(self, env_manager):
599
+ self.env_manager = env_manager
600
+ self.conn = None
601
+ self.cursor = None
602
+
603
+ def __enter__(self):
604
+ self.conn = sqlite3.connect(self.env_manager.db_path)
605
+ self.cursor = self.conn.cursor()
606
+ self.cursor.execute("BEGIN TRANSACTION")
607
+ return self
608
+
609
+ def __exit__(self, exc_type, exc_val, exc_tb):
610
+ if exc_type is None:
611
+ self.conn.commit()
612
+ else:
613
+ self.conn.rollback()
614
+ from .logger import logger
615
+ logger.error(f"事务执行失败: {exc_val}")
616
+ self.conn.close()
617
+
618
+ def _check_auto_snapshot(self):
619
+ from .logger import logger
620
+
621
+ if not hasattr(self, '_last_snapshot_time') or self._last_snapshot_time is None:
622
+ self._last_snapshot_time = time.time()
623
+
624
+ if not hasattr(self, '_snapshot_interval') or self._snapshot_interval is None:
625
+ self._snapshot_interval = 3600
626
+
627
+ current_time = time.time()
628
+
629
+ try:
630
+ time_diff = current_time - self._last_snapshot_time
631
+ if not isinstance(time_diff, (int, float)):
632
+ raiserr.register(
633
+ "ErisPulseEnvTimeDiffTypeError",
634
+ doc = "时间差应为数值类型",
635
+ )
636
+ raiserr.ErisPulseEnvTimeDiffTypeError(
637
+ f"时间差应为数值类型,实际为: {type(time_diff)}"
638
+ )
639
+
640
+ if not isinstance(self._snapshot_interval, (int, float)):
641
+ raiserr.register(
642
+ "ErisPulseEnvSnapshotIntervalTypeError",
643
+ doc = "快照间隔应为数值类型",
644
+ )
645
+ raiserr.ErisPulseEnvSnapshotIntervalTypeError(
646
+ f"快照间隔应为数值类型,实际为: {type(self._snapshot_interval)}"
647
+ )
648
+
649
+ if time_diff > self._snapshot_interval:
650
+ self._last_snapshot_time = current_time
651
+ self.snapshot(f"auto_{datetime.now().strftime('%Y%m%d_%H%M%S')}")
652
+
653
+ except Exception as e:
654
+ logger.error(f"自动快照检查失败: {e}")
655
+ self._last_snapshot_time = current_time
656
+ self._snapshot_interval = 3600
657
+
658
+ def set_snapshot_interval(self, seconds):
659
+ self._snapshot_interval = seconds
74
660
 
75
661
  def clear(self):
76
662
  conn = sqlite3.connect(self.db_path)
@@ -127,4 +713,99 @@ from ErisPulse import sdk
127
713
  from .logger import logger
128
714
  logger.error(f"配置项 {key} 不存在")
129
715
 
130
- env = EnvManager()
716
+ def __setattr__(self, key, value):
717
+ try:
718
+ self.set(key, value)
719
+ except Exception as e:
720
+ from .logger import logger
721
+ logger.error(f"设置配置项 {key} 失败: {e}")
722
+
723
+ def snapshot(self, name=None):
724
+ if not name:
725
+ name = datetime.now().strftime("%Y%m%d_%H%M%S")
726
+ snapshot_path = os.path.join(self.SNAPSHOT_DIR, f"{name}.db")
727
+
728
+ try:
729
+ # 快照目录
730
+ os.makedirs(self.SNAPSHOT_DIR, exist_ok=True)
731
+
732
+ # 安全关闭连接
733
+ if hasattr(self, "_conn") and self._conn is not None:
734
+ try:
735
+ self._conn.close()
736
+ except Exception as e:
737
+ from .logger import logger
738
+ logger.warning(f"关闭数据库连接时出错: {e}")
739
+
740
+ # 创建快照
741
+ shutil.copy2(self.db_path, snapshot_path)
742
+ from .logger import logger
743
+ logger.info(f"数据库快照已创建: {snapshot_path}")
744
+ return snapshot_path
745
+ except Exception as e:
746
+ from .logger import logger
747
+ logger.error(f"创建快照失败: {e}")
748
+ raise
749
+
750
+ def restore(self, snapshot_name):
751
+ snapshot_path = os.path.join(self.SNAPSHOT_DIR, f"{snapshot_name}.db") \
752
+ if not snapshot_name.endswith('.db') else snapshot_name
753
+
754
+ if not os.path.exists(snapshot_path):
755
+ from .logger import logger
756
+ logger.error(f"快照文件不存在: {snapshot_path}")
757
+ return False
758
+
759
+ try:
760
+ # 安全关闭连接
761
+ if hasattr(self, "_conn") and self._conn is not None:
762
+ try:
763
+ self._conn.close()
764
+ except Exception as e:
765
+ from .logger import logger
766
+ logger.warning(f"关闭数据库连接时出错: {e}")
767
+
768
+ # 执行恢复操作
769
+ shutil.copy2(snapshot_path, self.db_path)
770
+ self._init_db() # 恢复后重新初始化数据库连接
771
+ from .logger import logger
772
+ logger.info(f"数据库已从快照恢复: {snapshot_path}")
773
+ return True
774
+ except Exception as e:
775
+ from .logger import logger
776
+ logger.error(f"恢复快照失败: {e}")
777
+ return False
778
+
779
+ def list_snapshots(self):
780
+ snapshots = []
781
+ for f in os.listdir(self.SNAPSHOT_DIR):
782
+ if f.endswith('.db'):
783
+ path = os.path.join(self.SNAPSHOT_DIR, f)
784
+ stat = os.stat(path)
785
+ snapshots.append((
786
+ f[:-3], # 去掉.db后缀
787
+ datetime.fromtimestamp(stat.st_ctime),
788
+ stat.st_size
789
+ ))
790
+ return sorted(snapshots, key=lambda x: x[1], reverse=True)
791
+
792
+ def delete_snapshot(self, snapshot_name):
793
+ snapshot_path = os.path.join(self.SNAPSHOT_DIR, f"{snapshot_name}.db") \
794
+ if not snapshot_name.endswith('.db') else snapshot_name
795
+
796
+ if not os.path.exists(snapshot_path):
797
+ from .logger import logger
798
+ logger.error(f"快照文件不存在: {snapshot_path}")
799
+ return False
800
+
801
+ try:
802
+ os.remove(snapshot_path)
803
+ from .logger import logger
804
+ logger.info(f"快照已删除: {snapshot_path}")
805
+ return True
806
+ except Exception as e:
807
+ from .logger import logger
808
+ logger.error(f"删除快照失败: {e}")
809
+ return False
810
+
811
+ env = EnvManager()