切换 ORM 至 SQLAlchemy 2.0 #100
he0119
announced in
Announcements
Replies: 3 comments
-
新的模型定义如下。 nonebot-plugin-datastore/tests/registry/plugin2/models.py Lines 1 to 26 in f45b5dc |
Beta Was this translation helpful? Give feedback.
0 replies
-
迁移脚本可以通过切换到当时的模型定义重新生成,注意 下面以一个 脚本 为例 """empty message
Revision ID: 6b6cd695b2e7
Revises:
Create Date: 2023-02-06 19:18:07.691156
"""
import sqlalchemy as sa
-import sqlmodel
from alembic import op
# revision identifiers, used by Alembic.
revision = "6b6cd695b2e7"
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"plugin2_example",
sa.Column("id", sa.Integer(), nullable=False),
- sa.Column("message", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
+ sa.Column("message", sa.String(255), nullable=False),
sa.PrimaryKeyConstraint("id"),
)
op.create_table(
"plugin2_test",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("example_id", sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(
["example_id"],
["plugin2_example.id"],
),
sa.PrimaryKeyConstraint("id"),
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table("plugin2_test")
op.drop_table("plugin2_example")
# ### end Alembic commands ### 只需将从 SQLModel 中导入的类型修改为 SQLAlchemy 的即可。甚至很多类型本来就是从 SQLAlchemy 中导入的。
|
Beta Was this translation helpful? Give feedback.
0 replies
-
新的查询语句,几乎和以前没有区别,只需要将以前从 SQLModel 中导入的东西切换为从 SQLAlchemy 中导入。但切换之后类型标注恢复正常。 -from sqlmodel import select
+from sqlalchemy import select
async with create_session() as session:
statement = select(Example)
- result = await session.exec(statement) # type: ignore
- example = cast(Example, result.one())
+ example = (await session.scalars(statement)).one()
assert example.message == "post" |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
准备在下个版本将 ORM 切换至 SQLAlchemy 2.0。SQLModel 现在基本处于没有人维护的状态,而且 typing 也有问题,特别不爽。
我去 尝试 了一下 SQLAlchemy 2.0,各种 typing 都很舒服。并且定义模型的方法与 SQLModel 类似,使用起来也比较方便。
之后会尝试写一个简单的迁移步骤,主要需要修改的地方在模型定义与迁移脚本。
Beta Was this translation helpful? Give feedback.
All reactions