Package: nonebot-plugin-orm
NoneBot Plugin ORM✨ NoneBot 数据库支持插件 ✨安装pipinstallnonebot-plugin-orm
poetryaddnonebot-plugin-orm
pdmaddnonebot-plugin-orm# 无需配置、开箱即用的默认依赖pipinstallnonebot-plugin-orm[default]# 特定数据库后端的依赖pipinstallnonebot-plugin-orm[mysql]pipinstallnonebot-plugin-orm[postgresql]pipinstallnonebot-plugin-orm[sqlite]# 特定数据库驱动的依赖pipinstallnonebot-plugin-orm[asyncmy]pipinstallnonebot-plugin-orm[aiomysql]pipinstallnonebot-plugin-orm[psycopg]pipinstallnonebot-plugin-orm[asyncpg]pipinstallnonebot-plugin-orm[aiosqlite]使用方式ORMModel 依赖注入fromnonebot.adaptersimportEventfromnonebot.paramsimportDependsfromnonebotimportrequire,on_messagefromsqlalchemy.ormimportMapped,mapped_columnrequire("nonebot_plugin_orm")fromnonebot_plugin_ormimportModel,async_scoped_sessionmatcher=on_message()defget_user_id(event:Event)->str:returnevent.get_user_id()classUser(Model):id:Mapped[int]=mapped_column(primary_key=True)user_id:Mapped[str]=Depends(get_user_id)@matcher.handle()asyncdef_(event:Event,sess:async_scoped_session,user:User|None):ifuser:awaitmatcher.finish(f"Hello,{user.user_id}")sess.add(User(user_id=get_user_id(event)))awaitsess.commit()awaitmatcher.finish("Hello, new user!")SQL 依赖注入fromsqlalchemyimportselectfromnonebot.adaptersimportEventfromnonebot.paramsimportDependsfromnonebotimportrequire,on_messagefromsqlalchemy.ormimportMapped,mapped_columnrequire("nonebot_plugin_orm")fromnonebot_plugin_ormimportModel,SQLDepends,async_scoped_sessionmatcher=on_message()defget_session_id(event:Event)->str:returnevent.get_session_id()classSession(Model):id:Mapped[int]=mapped_column(primary_key=True)session_id:Mapped[str]@matcher.handle()asyncdef_(event:Event,sess:async_scoped_session,session:Session|None=SQLDepends(select(Session).where(Session.session_id==Depends(get_session_id))),):ifsession:awaitmatcher.finish(f"Hello,{session.session_id}")sess.add(Session(session_id=get_session_id(event)))awaitsess.commit()awaitmatcher.finish("Hello, new user!")CLI依赖NB CLI$nb ormUsage:nb orm [OPTIONS] COMMAND [ARGS]...Options:-c,--config FILE  可选的配置文件；默认为 ALEMBIC_CONFIG 环境变量的值，或者 "alembic.ini"（如果存在）-n,--name TEXT    .ini 文件中用于 Alembic 配置的小节的名称  [default: alembic]-xTEXT            自定义 env.py 脚本使用的其他参数，例如：-x setting1=somesetting -xsetting2=somesetting-q,--quite        不要输出日志到标准输出--helpShow this message and exit.Commands:branches显示所有的分支。check检查数据库是否与模型定义一致。current显示当前的迁移。downgrade回退到先前版本。edit使用 $EDITOR 编辑迁移脚本。ensure_version创建版本表。heads显示所有的分支头。history显示迁移的历史。init初始化脚本目录。list_templates列出所有可用的模板。merge合并多个迁移。创建一个新的迁移脚本。revision创建一个新迁移脚本。show显示迁移的信息。stamp将数据库标记为特定的迁移版本，不运行任何迁移。upgrade升级到较新版本。配置项sqlalchemy_database_url默认数据库连接 URL。
参见：Engine Configuration — SQLAlchemy 2.0 DocumentationSQLALCHEMY_DATABASE_URL=sqlite+aiosqlite://sqlalchemy_bindsbind keys 到AsyncEngine选项的映射。值可以是数据库连接 URL、AsyncEngine选项字典或者AsyncEngine实例。SQLALCHEMY_BINDS='{"":"sqlite+aiosqlite://","nonebot_plugin_user":{"url":"postgresql+asyncpg://scott:tiger@localhost/mydatabase","echo":true}}'sqlalchemy_echo所有AsyncEngine的echo和echo_pool选项的默认值。用于快速调试连接和 SQL 生成问题。SQLALCHEMY_ECHO=truesqlalchemy_engine_options所有AsyncEngine的默认选项字典。
参见：Engine Configuration — SQLAlchemy 2.0 DocumentationSQLALCHEMY_ENGINE_OPTIONS='{"pool_size":5,"max_overflow":10,"pool_timeout":30,"pool_recycle":3600,"echo":true}'sqlalchemy_session_optionsAsyncSession的选项字典。
参见：Session API — SQLAlchemy 2.0 DocumentationSQLALCHEMY_SESSION_OPTIONS='{"autoflush":false,"autobegin":true,"expire_on_commit":true}'alembic_config配置文件路径或AlembicConfig实例。ALEMBIC_CONFIG=alembic.inialembic_script_location脚本目录路径。ALEMBIC_SCRIPT_LOCATION=migrationsalembic_version_locations迁移脚本目录路径或分支标签到迁移脚本目录路径的映射。ALEMBIC_VERSION_LOCATIONS=migrations/versionsALEMBIC_VERSION_LOCATIONS='{"":"migrations/versions","nonebot_plugin_user":"src/nonebot_plugin_user/versions","nonebot_plugin_chatrecorder":"migrations/versions/nonebot_plugin_chatrecorder"}'alembic_contextMigrationContext的选项字典。
参见：Runtime Objects — Alembic 1.12.0 documentationALEMBIC_CONTEXT='{"render_as_batch":true}'alembic_startup_check是否在启动时检查数据库与模型定义的一致性。ALEMBIC_STARTUP_CHECK=true