二:Recovery models(恢复模式)

本文介绍了SQL Server数据库中的三种恢复模式:简单、完全及大日志恢复模式,并通过实例对比了不同模式下数据恢复的可能性及限制。同时提供了查询当前数据库恢复模式的脚本以及如何更改数据库恢复模式的方法。

For each database that you create in SQL Server, with the exception of the system databases, you can configure it to use one of three possible recovery models (simple, full, bulk-logged).  Here is a simple script to display the recovery models of all on-line databases:

在数据库中创建的每个数据库,除了系统数据之外,你都能配置三种恢复模式(简单、完全、大量日志)中的一个。如下是显示在线数据库的恢复模式:

SELECT name, (SELECT DATABASEPROPERTYEX(name, 'RECOVERY')) RecoveryModel FROM master..sysdatabases ORDER BY name

If you are running SQL Server 2005 or later, you can use this script instead:

如果你运行在SQL Server 2005或者更高的版本上,你可以使用如下脚本代替:

SELECT name, recovery_model_desc FROM master.sys.databases ORDER BY name

This is how you can change a database's recovery model to the simple recovery model:

如下是教你改变数据库的恢复模式成简单恢复模式:

ALTER DATABASE AdventureWorks SET RECOVERY SIMPLE

 to the full recovery model:

改成完全恢复模式:

ALTER DATABASE AdventureWorks SET RECOVERY FULL

and to the bulk-logged recovery model:

改成大日志恢复模式:

ALTER DATABASE AdventureWorks SET RECOVERY BULK_LOGGED

Which recovery model do you need to use?  It depends on how much data you can afford to lose.  Let's use the following diagram to illustrate the difference between the recovery models, where a full database backup is performed at 9:00 a.m, and 11 a.m.

你要使用哪种恢复模式?那是取决于你能承担的起丢失多少数据。让我们用下面的图来解释恢复模式之前的区别,下面这张图是一个数据库在9:00am 和11:00am完成的完全备份。

 

The simple recovery model(简单恢复模式)

 Assume that there was a hardware failure at 10:45  a.m.  If the database was using the simple recovery model, you would have lost 105 minutes of work.  The latest point at which you can recover the database to is 9:00 a.m, since that was the time the last full backup that was made.  You could schedule differential backups to run periodically e.g.

 假设硬件在 10:45am坏了。如果数据库采用的是简单恢复模式,你将丢失105分钟的数据。你最近的恢复时间点是你在9:00am做的完全备份。你可以规划差异备份定期进行。例如:

 

In this case, you would lose 45 minutes of work.  Now, assuming that a user deleted a critical table at 9:50 a.m.  Can you recover to the point in time just before the deletion?  No.  The differential backup contains only the changed data pages.  It cannot be used to restore to a specific point in time.  You'll have to restore the database to its 9 a.m state, and redo 49 minutes of work.  Then, you'll also need to redo the work that was performed after the deletion up to the time the error was discovered.

在这种情况下,你将丢失45分钟的数据。现在,我们假设用户在9:50删除了主要的表。你能恢复到删除的那个时间点前数据吗?不能。差异备份只包含了数据的变化页,他不能用于去恢复特定时间点的数据。你将不得不去将数据库恢复到9:00am,然后重做49分钟的工作。此刻,你也必须去完成删除数据时间之后到发现错误之间的工作。

The full recovery model(完全恢复模式)

If no transaction log backups are made between 9 a.m and 11 a.m, you would face the same situation as you would if the database had been using the simple recovery model. In addition, your transaction log file would be much larger, as SQL Server will not truncate committed and checkpointed transactions until they have been backed up.

如果你没做事物日志备份在 9:00至11:00之前,你将面对的同样的情况就和你使用的简单恢复模式一样。另外,你的事务日志会非常大,因为SQL Server不会删除已经提交和已经CheckPoint的事务,直到它们被备份。

转载于:https://www.cnblogs.com/huaan011/p/4290435.html

# E:\AI_System\agent\cognitive_architecture.py import sys import logging import json import time import threading from agent.base_module import UnifiedCognitiveModule from core.module_manager import ModuleManager from core.message_bus import MessageBus from core.message import Message, MessageType from agent.environment_interface import EnvironmentInterface from agent.health_monitor import HealthMonitor class CognitiveSystem(UnifiedCognitiveModule): """核心认知系统 - 完整优化版""" VERSION = "1.6.0" DEFAULT_CONFIG = { "reasoning_depth": 3, "memory_limit": 1000, "auto_reflection": True, "learning_threshold": 0.8, "error_recovery": True, "max_concurrent_tasks": 5, "module_auto_recovery": True } def __init__(self, name: str, model_manager, config: dict = None): # 初始化基类 super().__init__( name=name, coordinator=self, config=config or self.DEFAULT_CONFIG ) # 关键修复:创建消息总线实例 self.message_bus = MessageBus() # 模型管理器 self.model_manager = model_manager # 初始化模块管理器 self.module_manager = ModuleManager(coordinator=self) # 命令处理器映射 self.command_handlers = { "help": self.handle_help, "hi": self.handle_greeting, "hello": self.handle_greeting, "你好": self.handle_greeting, "在吗": self.handle_greeting, "status": self.handle_status, "mode": self.handle_mode, "models": self.handle_models, "model": self.handle_models, "diagnose": self.handle_diagnose, "modules": self.handle_modules, "load": self.handle_load_module, "unload": self.handle_unload_module, "reload": self.handle_reload_module, "exit": self.handle_exit, "quit": self.handle_exit } # 系统状态 self.mode = "TASK_EXECUTION" self.memory = { "short_term": [], "long_term": {}, "last_accessed": time.time() } # 添加running属性(修复线程监控问题) self.running = True # 启动模块监控线程 self.monitor_thread = threading.Thread(target=self._monitor_modules, daemon=True) self.monitor_thread.start() # 模块初始化状态 self.initialized = False def initialize(self) -> bool: """初始化认知系统""" try: self.logger.info(f"✅ 认知系统初始化开始 (版本 {self.VERSION})") # 注册核心模块 self.module_manager.register_module("EnvironmentInterface", EnvironmentInterface) self.module_manager.register_module("HealthMonitor", HealthMonitor) # 加载环境接口模块 env_config = self.config.get("environment", {}) if self.module_manager.load_module("EnvironmentInterface", env_config): self.logger.info("✅ 环境接口模块加载成功") else: self.logger.error("❌ 环境接口模块加载失败") # 加载健康监控模块 health_config = self.config.get("health", {"interval": 15}) if self.module_manager.load_module("HealthMonitor", health_config): self.logger.info("✅ 健康监控模块加载成功") else: self.logger.error("❌ 健康监控模块加载失败") # 初始化完成 self.initialized = True self.logger.info(f"✅ 认知系统初始化完成 (模式: {self.mode})") return True except Exception as e: self.logger.error(f"❌ 认知系统初始化失败: {str(e)}", exc_info=True) return False def shutdown(self) -> bool: """关闭认知系统""" try: self.logger.info("🛑 关闭认知系统开始") # 设置运行标志为False self.running = False # 停止监控线程 if self.monitor_thread.is_alive(): self.monitor_thread.join(timeout=5.0) # 卸载所有模块 self.module_manager.unload_all_modules() # 清理资源 self.message_bus.shutdown() self.module_manager = None self.initialized = False self.logger.info("✅ 认知系统已完全关闭") return True except Exception as e: self.logger.error(f"❌ 关闭系统失败: {str(e)}", exc_info=True) return False def process(self, input_data: dict) -> dict: """处理输入数据""" try: self.logger.debug(f"🧠 处理输入: {type(input_data)}") # 处理不同类型输入 if isinstance(input_data, str): return self.process_command(input_data) elif isinstance(input_data, dict): command = input_data.get("command") if command: return self.process_command(command) return {"error": "无效的输入格式"} else: return {"error": "不支持的输入类型"} except Exception as e: self.logger.error(f"处理输入失败: {str(e)}", exc_info=True) return {"error": f"处理失败: {str(e)}"} def process_command(self, command: str) -> dict: """处理用户命令(返回字典格式)""" try: self.logger.info(f"🧠 处理命令: {command}") # 分割命令和参数 parts = command.split(maxsplit=1) cmd = parts[0].lower() arg = parts[1] if len(parts) > 1 else "" # 查找命令处理器 handler = self.command_handlers.get(cmd, self.handle_default) # 解析JSON格式输入 if arg.startswith("{"): try: arg = json.loads(arg) except json.JSONDecodeError: pass result = handler(arg) # 确保返回字典格式 if isinstance(result, str): return {"response": result} elif isinstance(result, dict): return result else: return {"response": str(result)} except Exception as e: self.logger.error(f"命令处理失败: {str(e)}", exc_info=True) return {"error": f"处理命令时出错: {str(e)}"} # === 命令处理函数 === def handle_greeting(self, arg: str) -> str: """处理问候命令""" return f"你好,我是{self.name}!有什么可以帮您?" def handle_help(self, arg: str) -> str: """处理帮助命令""" help_text = """ === 高级命令系统 === 基础命令: help - 显示此帮助信息 exit/quit - 退出系统 status - 查看系统状态 mode [mode]- 切换工作模式 (reflect, task, learn) 系统控制: models - 显示已加载模型 model - 同 models diagnose - 执行系统诊断 config [key] [value] - 修改配置 modules - 查看模块状态 load [module] - 加载模块 unload [module] - 卸载模块 reload [module] - 重新加载模块 多行输入: 输入多行命令时,在最后一行以 ;; 结束 """ return help_text def handle_status(self, arg: str) -> str: """处理状态查询命令""" return ( f"系统状态:\n" f"- 认知系统: {self.name} v{self.VERSION}\n" f"- 当前模式: {self.mode}\n" f"- 最后访问: {time.ctime(self.memory['last_accessed'])}\n" f"- 短期记忆: {len(self.memory['short_term'])}/{self.config['memory_limit']} 条\n" f"- 运行时间: {time.time() - self.start_time:.1f}秒" ) def handle_mode(self, arg: str) -> str: """处理模式切换命令""" if not arg: return "请指定模式: reflect, task, learn" mode_map = { "reflect": "SELF_REFLECTION", "task": "TASK_EXECUTION", "learn": "LEARNING" } new_mode = mode_map.get(arg.lower(), "") if new_mode: self.set_mode(new_mode) return f"已切换到 {new_mode} 模式" return f"❌ 无效模式: {arg} (可用选项: reflect, task, learn)" def handle_models(self, arg: str) -> str: """处理模型查询命令""" try: # 获取模型信息 model_registry = self.model_manager._persistent_registry loaded_models = self.model_manager.loaded_models # 构建模型信息列表 models_info = [] for name, info in model_registry.items(): status = "✅ 已加载" if name in loaded_models else "❌ 未加载" models_info.append(f"- {name}: {info.get('path', '')} ({status})") return "已配置模型:\n" + "\n".join(models_info) except Exception as e: return f"❌ 获取模型信息失败: {str(e)}" def handle_diagnose(self, arg: str) -> str: """处理诊断命令 - 增强版""" try: response = "系统诊断报告:\n" # 模块状态 loaded_modules = self.module_manager.list_modules() response += f"- 已加载模块: {len(loaded_modules)}个\n" # 尝试获取健康监控报告 health_monitor = self.module_manager.get_module("HealthMonitor") if health_monitor: health_report = health_monitor.get_health_status() for module, status in health_report.items(): response += f"- {module}: {status['status']} ({status.get('message', '')})\n" else: response += "- 健康监控模块未加载\n" return response except Exception as e: return f"❌ 执行诊断失败: {str(e)}" def handle_modules(self, arg: str) -> str: """处理模块查询命令""" loaded_modules = self.module_manager.list_modules() registered_modules = list(self.module_manager.module_classes.keys()) response = "已注册模块:\n" + "\n".join([f"- {name}" for name in registered_modules]) response += "\n\n已加载模块:\n" + "\n".join([f"- {name}" for name in loaded_modules]) return response def handle_load_module(self, arg: str) -> str: """处理模块加载命令""" if not arg: return "请指定要加载的模块名称" module_config = self.config.get("modules", {}).get(arg, {}) success = self.module_manager.load_module(arg, module_config) return f"✅ 模块 {arg} 加载成功" if success else f"❌ 模块 {arg} 加载失败" def handle_unload_module(self, arg: str) -> str: """处理模块卸载命令""" if not arg: return "请指定要卸载的模块名称" success = self.module_manager.unload_module(arg) return f"✅ 模块 {arg} 卸载成功" if success else f"❌ 模块 {arg} 卸载失败" def handle_reload_module(self, arg: str) -> str: """处理模块重载命令""" if not arg: return "请指定要重载的模块名称" module_config = self.config.get("modules", {}).get(arg, {}) success = self.module_manager.reload_module(arg, module_config) return f"✅ 模块 {arg} 重载成功" if success else f"❌ 模块 {arg} 重载失败" def handle_exit(self, arg: str) -> dict: """处理退出命令""" return {"action": "shutdown", "message": "正在关闭系统..."} def handle_default(self, command: str) -> str: """默认命令处理器""" return f"正在处理您的请求: {command}..." # === 内部辅助方法 === def _monitor_modules(self): """监控模块健康状态的后台线程""" while self.running: time.sleep(10) # 每10秒检查一次 try: if self.module_manager: health_monitor = self.module_manager.get_module("HealthMonitor") if health_monitor: status_report = health_monitor.get_health_status() self.logger.debug(f"模块健康报告: {status_report}") # 自动恢复异常模块 if self.config.get("module_auto_recovery", True): for module_name, status in status_report.items(): if status.get("status") != "healthy": self.logger.warning(f"⚠️ 模块 {module_name} 状态异常,尝试恢复...") self.module_manager.reload_module(module_name) except Exception as e: self.logger.error(f"模块监控错误: {str(e)}") def get_current_mode(self): """获取当前模式""" return self.mode def set_mode(self, new_mode: str): """切换模式""" valid_modes = ["SELF_REFLECTION", "TASK_EXECUTION", "LEARNING"] if new_mode in valid_modes: self.mode = new_mode self.logger.info(f"切换到 {new_mode} 模式") return True else: self.logger.warning(f"无效模式: {new_mode}") return False def get_health_status(self) -> dict: """获取健康状态报告""" return { "status": "running" if self.running else "stopped", "version": self.VERSION, "mode": self.mode, "memory_usage": f"{len(self.memory['short_term'])}/{self.config['memory_limit']}", "last_accessed": self.memory["last_accessed"], "modules": self.module_manager.list_modules() if self.module_manager else [] } “# 在 CognitiveOrchestrator 类中添加以下方法 def get_module(self, module_name: str): """获取模块实例(安全访问)""" return self.modules.get(module_name, None) def get_modules(self): """获取所有模块实例""" return self.modules ”
最新发布
08-31
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值