Skip to main content
<!-- markdownlint-disable MD033 MD036 MD041 -->

<p align="center">
<a href="https://v2.nonebot.dev/"><img src="https://v2.nonebot.dev/logo.png" width="200" height="200" alt="nonebot"></a>
</p>

<div align="center">

nonebot-plugin-sqlalchemy
============

_✨ NoneBot SQLAlchemy 封装插件 ✨_

</div>

<p align="center">
<a href="https://raw.githubusercontent.com/ssttkkl/nonebot-plugin-sqlalchemy/master/LICENSE">
<img src="https://img.shields.io/github/license/ssttkkl/nonebot-plugin-sqlalchemy.svg" alt="license">
</a>
<a href="https://pypi.python.org/pypi/nonebot-plugin-sqlalchemy">
<img src="https://img.shields.io/pypi/v/nonebot-plugin-sqlalchemy.svg" alt="pypi">
</a>
<img src="https://img.shields.io/badge/python-3.9+-blue.svg" alt="python">
</p>

为插件封装SQLAlchemy数据库访问,一个插件使用一个数据库。

对于数据存储较简单的场景,推荐使用[he0119/nonebot-plugin-datastore](https://github.com/he0119/nonebot-plugin-datastore)

## Get Started

### 1、定义data_source

```python
from nonebot import get_driver, require

# 注意必须先require再import
require("nonebot_plugin_sqlalchemy")
from nonebot_plugin_sqlalchemy import DataSource

# 必须使用支持asyncio的驱动器
db_conn_url = "postgresql+asyncpg://username:password@localhost:5432/database"
data_source = DataSource(get_driver(), db_conn_url)
```

### 2、定义映射
```python
from sqlalchemy.orm import mapped_column

@data_source.registry.mapped
class UserOrm:
__tablename__ = 'users'

id: int = mapped_column(primary_key=True, autoincrement=True)
username: str
password: str
nickname: str
```

### 3、在Matcher中使用

```python
from nonebot import on_command
from nonebot.adapters.onebot.v11 import MessageEvent
from nonebot.internal.matcher import Matcher
from sqlalchemy import select

login_matcher = on_command("login")


@login_matcher.handle()
async def handler(event: MessageEvent, matcher: Matcher):
username, password = event.get_plaintext().split(" ")

session = data_source.session()

stmt = select(UserOrm).where(UserOrm.username == username, UserOrm.password == password)
result = await session.execute(stmt)
user = result.scalar_one_or_none()

if user is not None:
await matcher.send(f"Hello, {user.nickname}")
```

通过`data_source.session()`获取AsyncSession对象,此处获取的session实际上是async_scoped_session。

在Matcher的一次执行过程中,多次调用`data_source.session()`获得的是同一个session,并且会在Matcher执行完毕后自动关闭。也就是说我们可以像下面这样使用:

```python
from nonebot import on_command
from nonebot.adapters.onebot.v11 import MessageEvent
from nonebot.internal.matcher import Matcher
from sqlalchemy import select
from typing import Optional

async def login(username: str, password: str) -> Optional[User]:
session = data_source.session()

stmt = select(UserOrm).where(UserOrm.username == username, UserOrm.password == password)
result = await session.execute(stmt)
user = result.scalar_one_or_none()

return user


login_matcher = on_command("login")


@login_matcher.handle()
async def handler(event: MessageEvent, matcher: Matcher):
username, password = event.get_plaintext().split(" ")
user = await login(username, password)
if user is not None:
await matcher.send(f"Hello, {user.nickname}")
```

参考:https://docs.sqlalchemy.org/en/14/orm/extensions/asyncio.html#using-asyncio-scoped-session

注意:务必保证一次Matcher执行过程不会在不同的Task中调用`data_source.session()`获取session(即不要使用`create_task()`或`ensure_future()`创建Task),否则可能出现错误。若有这样的需求,请参考下文的方法手动创建并管理session。


### 4、在Matcher之外使用

在Matcher之外(如on_bot_connect等钩子函数中,或者是APScheduler的定时任务中)则必须通过`AsyncSession(data_source.engine)`创建session。

```python
async def do_something():
async with AsyncSession(data_source.engine) as session:
# ...
```

Metadata

Release files for nonebot-plugin-sqlalchemy 0.2.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for nonebot-plugin-sqlalchemy 0.2.2
File Size Uploaded Provenance Actions
nonebot_plugin_sqlalchemy-0.2.2.tar.gz 4.7 kB Without provenance Details for nonebot_plugin_sqlalchemy-0.2.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for nonebot-plugin-sqlalchemy 0.2.2
File Interpreter ABI Platform Actions
nonebot_plugin_sqlalchemy-0.2.2-py3-none-any.whl Python 3 none any Details for nonebot_plugin_sqlalchemy-0.2.2-py3-none-any.whl

Total release size: 10.0 kB

Release files / nonebot_plugin_sqlalchemy-0.2.2.tar.gz

Download URL nonebot_plugin_sqlalchemy-0.2.2.tar.gz
Size 4.7 kB
Tags Source
SHA-256 checksum
How to use checksums
2b3f76768d9c08f8715d2d892499d3ca36a2b7a37eabe2eff06617551b04cf06
BLAKE2b-256 checksum
How to use checksums
d722db73b2b63cbc11ba94802e7ba49776358bafe213dff06fde86810e0b6149
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.9.17

Release files / nonebot_plugin_sqlalchemy-0.2.2-py3-none-any.whl

Download URL nonebot_plugin_sqlalchemy-0.2.2-py3-none-any.whl
Size 5.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4ec310daafdea259cd0b81171313a8a3fc23d90edf18f75f298d14c58c7d4327
BLAKE2b-256 checksum
How to use checksums
f297d7b87eee47f6c9beabcea61991c0c03134f947010729d204c71e7b0177da
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.9.17

Security for nonebot-plugin-sqlalchemy 0.2.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page