Skip to content

Update some usage documents #27

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions docs/advanced/commit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
SQLAlchemy CRUD Plus 内部很多方法都提供了 `commit` 参数,默认值为 `False`,它既不会执行提交操作,也不包含 `flush`
等行为,要想真正写入到数据库,你可以通过以下几种方案

## `commit=True`

这通常适用于手动创建的 [session 生成器](https://fastapi.tiangolo.com/tutorial/sql-databases/?h=get_db#create-a-dependency),
SQLAlchemy CRUD Plus 将在内部自动执行提交

```py hl_lines="31"
from fastapi import FastAPI, Depends

--8<-- "docs/ext/get_db.py"

app = FastAPI()


class CreateIns(BaseModel):
# your pydantic schema
pass


@app.post('/api', summary='新增一条数据')
async def create(self, obj: CreateIns, db: AsyncSession = Depends(get_db)) -> None:
await self.create_model(db, obj, commit=True)
```

## `begin()`

适用于自动提交,[这一切都由 sqlalchemy 在内部完成](https://docs.sqlalchemy.org.cn/en/20/orm/session_transaction.html)
,因此,用户无需重复调用 commit 方法

```py hl_lines="9"
--8<-- "docs/ext/async_db_session.py"


async def create(self, obj: CreateIns) -> None:
async with async_db_session.begin() as db:
await self.create_model(db, obj)
```
2 changes: 1 addition & 1 deletion docs/advanced/primary_key.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ async def delete(self, db: AsyncSession, primary_key: int) -> int:

## 主键定义

!!! warning 自动主键
!!! tip 自动主键

我们在 SQLAlchemy CRUD Plus 内部通过 [inspect()](https://docs.sqlalchemy.org/en/20/core/inspection.html) 自动搜索表主键,
而非强制绑定主键列必须命名为 id,感谢 [@DavidSche](https://github.com/DavidSche) 提供帮助
Expand Down
6 changes: 0 additions & 6 deletions docs/changelog.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
# Change Logs

* Prepare for 1.3.0 release. PR [#22](https://github.com/fastapi-practices/sqlalchemy-crud-plus/pull/22) by [@wu-clan](https://github.com/wu-clan).
* Add mor and **gor** filters . PR [#21](https://github.com/fastapi-practices/sqlalchemy-crud-plus/pull/21) by [@wu-clan](https://github.com/wu-clan).
* Prepare for 1.2.0 release. PR [#20](https://github.com/fastapi-practices/sqlalchemy-crud-plus/pull/20) by [@wu-clan](https://github.com/wu-clan).
* Add select and sort constructors. PR [#19](https://github.com/fastapi-practices/sqlalchemy-crud-plus/pull/19) by [@wu-clan](https://github.com/wu-clan).
* Add ci for change logs. PR [#18](https://github.com/fastapi-practices/sqlalchemy-crud-plus/pull/18) by [@wu-clan](https://github.com/wu-clan).

## 1.4.0 - 2024-08-27

### What's Changed
Expand Down
2 changes: 0 additions & 2 deletions docs/ext/async_db_session.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine

async_engine = create_async_engine('数据库连接', future=True)
Expand Down
18 changes: 18 additions & 0 deletions docs/ext/get_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine

async_engine = create_async_engine('数据库连接', future=True)
async_db_session = async_sessionmaker(async_engine, autoflush=False, expire_on_commit=False)


async def get_db() -> AsyncSession:
"""
session 生成器
"""
session = async_db_session()
try:
yield session
except Exception as se:
await session.rollback()
raise se
finally:
await session.close()
2 changes: 2 additions & 0 deletions docs/ext/model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
6 changes: 6 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@
pdm add sqlalchemy-crud-plus
```

=== "uv"

```sh
uv add sqlalchemy-crud-plus
```

## 示例

=== "api.py"
Expand Down
6 changes: 6 additions & 0 deletions docs/installing.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,9 @@
```sh
pdm add sqlalchemy-crud-plus
```

=== "uv"

```sh
uv add sqlalchemy-crud-plus
```
21 changes: 1 addition & 20 deletions docs/usage/create_model.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ async def create_model(
) -> Model:
````

!!! note "create_model 独特的关键字参数"
!!! note "create_model <独特>的关键字参数"

除了必须传入 obj schema 外,还可以通过关键字入参,传入非 schema
参数,比如,对于某些特定场景,其中一个字段并不是通用的,也不需要进行输入控制,只需在写入时赋予指定值,那么你可以使用关键字入参即可
Expand All @@ -24,26 +24,7 @@ async def create_model(
1. 在数据被最终写入前,所有入参(schema 和关键字参数)都会赋值给 SQLAlchemy 模型,即便你传入了非模型数据,
这也是安全的,因为它不会被模型所引用

## 提交

此方法提供 `commit` 参数,默认值为 False,它既不会执行提交操作,也不包含 `flush` 等行为,要想真正写入到数据库,你可以通过以下几种方案

1. 设置 `commit=True` 手动提交

```py hl_lines="2"
async def create(self, db: AsyncSession, obj: CreateIns) -> None:
await self.create_model(db, obj, commit=True)
```

2. 使用 `begin()` 事务自动提交

```py hl_lines="9"
--8<-- "docs/ext/async_db_session.py"

async def create(self, obj: CreateIns) -> None:
async with async_db_session.begin() as db:
await self.create_model(db, obj)
```

## 示例

Expand Down
2 changes: 1 addition & 1 deletion docs/usage/create_models.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ async def create_models(
) -> list[Model]:
```

此方法提供 `commit` 参数,详见:[提交](./create_model.md/#_1)
此方法提供 `commit` 参数,详见:[提交](../advanced/commit.md)

## 示例

Expand Down
9 changes: 2 additions & 7 deletions docs/usage/delete_model.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ async def delete_model(

- 此方法使用主键 pk 参数,详见:[主键](../advanced/primary_key.md)

- 此方法提供 `commit` 参数,详见:[提交](./create_model.md/#_1)
- 此方法提供 `commit` 参数,详见:[提交](../advanced/commit.md)

## 示例

```py title="delete_model" hl_lines="21"
```py title="delete_model" hl_lines="18"
from pydantic import BaseModel

from sqlalchemy_crud_plus import CRUDPlus
Expand All @@ -29,11 +29,6 @@ class ModelIns(Base):
custom_id: Mapped[int] = mapped_column(primary_key=True, index=True, autoincrement=True)


class CreateIns(BaseModel):
# your pydantic schema
pass


class CRUDIns(CRUDPlus[ModelIns]):
async def delete(self, db: AsyncSession, pk: int) -> int:
return await self.delete_model(db, pk)
Expand Down
11 changes: 3 additions & 8 deletions docs/usage/delete_model_by_column.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ async def delete_model_by_column(
) -> int:
```

- 此方法提供 `commit` 参数,详见:[提交](./create_model.md/#_1)
- 此方法提供 `commit` 参数,详见:[提交](../advanced/commit.md)

- 此方法可结合 [高级过滤器](../advanced/filter.md) 使用

Expand All @@ -23,13 +23,13 @@ async def delete_model_by_column(
此方法同时提供逻辑删除,将参数 `logical_deletion` 设置为 True,将不会从数据库中直接删除数据,而是通过更新的方式,
将数据库删除标志字段的值进行更新,你可以通过 `deleted_flag_column` 参数设置指定逻辑删除字段,默认为 `del_flag`

!!! warning "注意"
!!! tip

逻辑删除也允许同时删除多条,同样由参数 `allow_multiple` 和过滤器控制

## 示例

```py title="delete_model_by_column" hl_lines="21"
```py title="delete_model_by_column" hl_lines="16"
from pydantic import BaseModel

from sqlalchemy_crud_plus import CRUDPlus
Expand All @@ -43,11 +43,6 @@ class ModelIns(Base):
pass


class CreateIns(BaseModel):
# your pydantic schema
pass


class CRUDIns(CRUDPlus[ModelIns]):
async def delete(self, db: AsyncSession) -> int:
return await self.delete_model_by_column(db, name="foo")
Expand Down
7 changes: 1 addition & 6 deletions docs/usage/select_model.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ async def select_model(

## 示例

```py title="select_model" hl_lines="21"
```py title="select_model" hl_lines="18"
from pydantic import BaseModel

from sqlalchemy_crud_plus import CRUDPlus
Expand All @@ -26,11 +26,6 @@ class ModelIns(Base):
custom_id: Mapped[int] = mapped_column(primary_key=True, index=True, autoincrement=True)


class CreateIns(BaseModel):
# your pydantic schema
pass


class CRUDIns(CRUDPlus[ModelIns]):
async def select(self, db: AsyncSession, pk: int) -> ModelIns:
return await self.select_model(db, pk)
Expand Down
7 changes: 1 addition & 6 deletions docs/usage/select_model_by_column.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ async def select_model_by_column(

## 示例

```py title="select_model_by_cloumn" hl_lines="21"
```py title="select_model_by_cloumn" hl_lines="16"
from pydantic import BaseModel

from sqlalchemy_crud_plus import CRUDPlus
Expand All @@ -24,11 +24,6 @@ class ModelIns(Base):
pass


class CreateIns(BaseModel):
# your pydantic schema
pass


class CRUDIns(CRUDPlus[ModelIns]):
async def create(self, db: AsyncSession) -> ModelIns:
return await self.select_model_by_column(db, name="foo")
Expand Down
7 changes: 1 addition & 6 deletions docs/usage/select_models.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ async def select_models(

## 示例

```py title="select_models" hl_lines="23"
```py title="select_models" hl_lines="18"
from typing import Sequence

from pydantic import BaseModel
Expand All @@ -26,11 +26,6 @@ class ModelIns(Base):
pass


class CreateIns(BaseModel):
# your pydantic schema
pass


class CRUDIns(CRUDPlus[ModelIns]):
async def create(self, db: AsyncSession) -> Sequence[ModelIns]:
return await self.select_models(db)
Expand Down
7 changes: 1 addition & 6 deletions docs/usage/select_models_order.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ async def select_models_order(

## 示例

```py title="select_models_order" hl_lines="23"
```py title="select_models_order" hl_lines="18"
from typing import Sequence

from pydantic import BaseModel
Expand All @@ -37,11 +37,6 @@ class ModelIns(Base):
pass


class CreateIns(BaseModel):
# your pydantic schema
pass


class CRUDIns(CRUDPlus[ModelIns]):
async def create(self, db: AsyncSession) -> Sequence[ModelIns]:
return await self.select_models_order(db, sort_columns=['name', 'age'], sort_orders=['asc', 'desc'])
Expand Down
4 changes: 2 additions & 2 deletions docs/usage/update_model.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ async def update_model(

- 此方法使用主键 pk 参数,详见:[主键](../advanced/primary_key.md)

- 此方法提供 `commit` 参数,详见:[提交](./create_model.md/#_1)
- 此方法提供 `commit` 参数,详见:[提交](../advanced/commit.md)

## 示例

```py title="update_model" hl_lines="21"
```py title="update_model" hl_lines="23"
from pydantic import BaseModel

from sqlalchemy_crud_plus import CRUDPlus
Expand Down
2 changes: 1 addition & 1 deletion docs/usage/update_model_by_column.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ async def update_model_by_column(
) -> int:
```

- 此方法提供 `commit` 参数,详见:[提交](./create_model.md/#_1)
- 此方法提供 `commit` 参数,详见:[提交](../advanced/commit.md)

- 此方法可结合 [高级过滤器](../advanced/filter.md) 使用

Expand Down
7 changes: 4 additions & 3 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ nav:
- 删除 - 条件过滤: usage/delete_model_by_column.md
- Advanced:
- 主键: advanced/primary_key.md
- 提交: advanced/commit.md
- 条件过滤: advanced/filter.md
- Changelog: changelog.md
theme:
Expand All @@ -31,19 +32,19 @@ theme:
code: Roboto Mono
palette:
- media: "(prefers-color-scheme)"
primary: deep purple
primary: green
toggle:
icon: material/brightness-auto
name: Switch to light mode
- media: "(prefers-color-scheme: light)"
scheme: default
primary: deep purple
primary: pink
toggle:
icon: material/brightness-7
name: Switch to dark mode
- media: "(prefers-color-scheme: dark)"
scheme: slate
primary: deep purple
primary: green
toggle:
icon: material/brightness-4
name: Switch to auto mode
Expand Down