【从零开始的rust web开发之路 三】orm框架sea-orm入门使用教程

2024-02-01 05:36

本文主要是介绍【从零开始的rust web开发之路 三】orm框架sea-orm入门使用教程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

【从零开始的rust web开发之路 三】orm框架sea-orm入门使用教程


文章目录

  • 前言
  • 一、引入依赖
  • 二、创建数据库连接
    • 简单链接
    • 连接选项
    • 开启日志调试
  • 三、生成实体
    • 安装sea-orm-cli
    • 创建数据库表
    • 使用sea-orm-cli命令生成实体文件代码
  • 四、增删改查实现
    • 新增数据
    • 主键查找
    • 条件查找
      • 查找用户名是admin的一条用户
      • 查找地址是郑州的所有用户
      • 查找地址是郑州并且用户名包含admin的所有用户
      • 分页查找
    • 修改数据
    • 删除数据
    • 数据库事务操作
  • 总结

前言

前两篇文件主要降了axum相关使用,这篇文章来讲讲orm相关框架。目前rust orm相关框架不多,比较主流的是sqlx,本文介绍的框架实在此基础上封装的一层,sql-orm同样也支持rust异步。

一、引入依赖

sea-orm = { version = "0.12", features = [ <DATABASE_DRIVER>, <ASYNC_RUNTIME>, "macros" ] }  #DATABASE_DRIVERASYNC_RUNTIME参数需要替换

DATABASE_DRIVER参数

  • sqlx-mysql-SQLx的MySQL
  • sqlx-postgres-SQLx
  • PostgreSQL的 sqlx-sqlite

ASYNC_RUNTIME参数

  • runtime-async-std-native-tls
  • runtime-tokio-native-tls
  • runtime-async-std-rustls
  • runtime-tokio-rustls
    这里我们选择引入tokio异步支持的,还要引入tokio
[dependencies]
sea-orm = { version = "0.12", features = [ "sqlx-mysql", "runtime-tokio-native-tls", "macros" ] }
tokio = { version = "1.35.1", features = ["full"] }

二、创建数据库连接

简单链接

let db: DatabaseConnection = Database::connect("protocol://username:password@host/database").await?;

举例子mysql数据库连接

   let db: DatabaseConnection = Database::connect("mysql://root:root@127.0.0.1:3307/test").await.unwrap();

后续查询选相关操作每次调用DatabaseConnection ,都会从池中获取和释放连接。
连接别的数据库可以看官方文档https://www.sea-ql.org/SeaORM/docs/next/install-and-config/connection/

连接选项

若要配置连接,请使用 ConnectOptions 接口
let mut opt = ConnectOptions::new("mysql://root:root@127.0.0.1:3307/test");
opt.max_connections(100).min_connections(5).connect_timeout(Duration::from_secs(8)).acquire_timeout(Duration::from_secs(8)).idle_timeout(Duration::from_secs(8)).max_lifetime(Duration::from_secs(8)).sqlx_logging(true).sqlx_logging_level(log::LevelFilter::Info).set_schema_search_path("my_schema"); // Setting default PostgreSQL schemalet db = Database::connect(opt).await?;

可以看ConnectOptions接口文档https://docs.rs/sea-orm/0.12.12/sea_orm/struct.ConnectOptions.html

开启日志调试

开发阶段需要打印相关日志,可以开启调试模式
features当中多一个[“debug-print”]

[dependencies]
sea-orm = { version = "0.12", features = [ "sqlx-mysql", "runtime-tokio-native-tls", "macros" ,"debug-print","with-chrono"] }
tokio = { version = "1.35.1", features = ["full"] }
chrono = "0.4.33"
tracing = "0.1.40"
tracing-subscriber = { version = "0.3.18",features = ["env-filter","time","local-time", ]}

然后需要执行一段初始化tracing-subscriber代码

    // 设置全局日志级别为 infolet env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"))//单独设置sea_orm.add_directive("sea_orm::driver=debug".parse().unwrap())//关闭sqlx自带的日志.add_directive("sqlx::query=off".parse().unwrap());

三、生成实体

安装sea-orm-cli

运行命令

cargo install sea-orm-cli

创建数据库表

CREATE TABLE `user` (`id` int NOT NULL AUTO_INCREMENT,`username` varchar(32) NOT NULL COMMENT '用户名称',`birthday` datetime DEFAULT NULL COMMENT '生日',`sex` char(1) DEFAULT NULL COMMENT '性别',`address` varchar(256) DEFAULT NULL COMMENT '地址',PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=utf8mb3

使用sea-orm-cli命令生成实体文件代码

在项目文件夹下运行命令,-o 是输出文件目录。相关参数配置可看文档https://www.sea-ql.org/SeaORM/docs/next/generate-entity/sea-orm-cli/

sea-orm-cli generate entity -u mysql://root:root@127.0.0.1:3307/test -o src/entity

在这里插入图片描述
在main文件加入entity模块即可。
生成的文件内容
在这里插入图片描述

在这里插入图片描述
指定表名

#[sea_orm(table_name = "cake", schema_name = "public")]
pub struct Model { ... }

指定列名

#[sea_orm(column_name = "name")]
pub name: String

四、增删改查实现

新增数据

先了解ActiveValue和ActiveModel
use entity::user::ActiveModel as UserModel;
let user: UserModel =  UserModel{id: ActiveValue::NotSet,username: ActiveValue::Set("你好".to_owned()),birthday: ActiveValue::Set(Some(Local::now().naive_local())),sex: ActiveValue::Set(Some("1".to_owned())),address: ActiveValue::Set(Some("address".to_owned())),};

这里我们创建UserModel的ActiveModel模型,里面的值是ActiveValue类型,NotSet是不设置值。
创建ActiveModel方法还有别的,比如通过JSON字符,具体的可以看文档https://www.sea-ql.org/SeaORM/docs/next/basic-crud/insert/#convert-activemodel-back-to-model
然后执行插入方法,具体代码如下

use chrono::{ Local};
use sea_orm::{ActiveModelTrait, ActiveValue, Database, DatabaseConnection, IntoActiveModel};pub mod entity;
use entity::user::Entity as UserDao;
use entity::user::ActiveModel as UserModel;
use entity::user::Model as Model;
#[tokio::main]
async fn main(){let db: DatabaseConnection = Database::connect("mysql://root:root@127.0.0.1:3307/test").await.unwrap();let user: UserModel =  UserModel{id: ActiveValue::NotSet,username: ActiveValue::Set("你好".to_owned()),birthday: ActiveValue::Set(Some(Local::now().naive_local())),sex: ActiveValue::Set(Some("1".to_owned())),address: ActiveValue::Set(Some("address".to_owned())),};
/*    let user: Model = Model{id: 1,username: "admin".to_string(),birthday: Some(Local::now().naive_local()),sex: Some("1".to_owned()),address: Some("address".to_owned()),};let active_model = user.into_active_model();*/let result = user.insert(&db).await.unwrap();println!("插入成功!:{:?}",result);
}

多个插入可以调用上述代码UserDao中的insert_many方法,传入ActiveModel数组

主键查找

use entity::user::Entity as UserDao;let option = UserDao::find_by_id(1).one(&db).await.unwrap();match option {None => {}Some(user) => println!("查询成功!:{:?}",user)}

条件查找

查找用户名是admin的一条用户

use crate::entity::user;use entity::user::Entity as UserDao;let result = UserDao::find().filter(user::Column::Username.eq("admin")).one(&db).await.unwrap();match result {None => {}Some(user) => println!("查询成功!:{:?}",user)}

查找地址是郑州的所有用户

    use crate::entity::user;use entity::user::Entity as UserDao;let result = UserDao::find().filter(user::Column::Address.eq("郑州")).all(&db).await.unwrap();println!("查询成功!:{:?}",result)

查找地址是郑州并且用户名包含admin的所有用户

    use crate::entity::user;use entity::user::Entity as UserDao;let result = UserDao::find().filter(Condition::all().add(user::Column::Address.eq("郑州")).add(user::Column::Username.like("%admin%"))).all(&db).await.unwrap();println!("查询成功!:{:?}",result)

分页查找

 
use crate::entity::user;use entity::user::Entity as UserDao;let mut paginator = UserDao::find().filter(Condition::all().add(user::Column::Address.eq("郑州")).add(user::Column::Username.like("%admin%"))).paginate(&db,50);//paginate(&db,50)此处第二个参数表示设置单页数量,此方法会返回Paginator对象。while let Some(user) = paginator.fetch_and_next().await.unwrap() {//循环从paginate取数据,每次取50条,页数加一,直到没有数据println!("查询成功!:{:?}",user)}

如果直接获取第几页数据怎么做,下面有方法

    use crate::entity::user;use entity::user::Entity as UserDao;let mut paginator = UserDao::find().filter(Condition::all().add(user::Column::Address.eq("郑州")).add(user::Column::Username.like("%admin%"))).paginate(&db,50);//此方法可直接取具体页数,注意是从零开始,需要前端页数加一let result = paginator.fetch_page(0).await;match result{Ok(vec_user) => {println!("{:?}", vec_user)}Err(_) => {}}

修改数据

修改主键为1的用用户名

    use entity::user::Entity as UserDao;let user = UserDao::find_by_id(1).one(&db).await.unwrap().unwrap();let mut active_model = user.into_active_model();active_model.username = ActiveValue::Set("修改后的用户名".to_owned());active_model.update(&db).await.unwrap();

如果想强制更新某个字段可以调用。

active_model.reset(user::Column::Address); //这样更新时字段就会强制带上,可以实现把字段置空

删除数据

很简单

    use entity::user::Entity as UserDao;let res = UserDao::delete_by_id(1).exec(&db).await.unwrap();

或者还有一种方法

    use entity::user::Entity as UserDao;let res = UserDao::find_by_id(1).one(&db).await.unwrap().unwrap();let active_model = res.into_active_model();active_model.delete(&db).await.unwrap();

数据库事务操作

可以手动调用db的begin和commit方法,以下是官方例子

let txn = db.begin().await?;bakery::ActiveModel {name: Set("SeaSide Bakery".to_owned()),profit_margin: Set(10.4),..Default::default()
}
.save(&txn)
.await?;bakery::ActiveModel {name: Set("Top Bakery".to_owned()),profit_margin: Set(15.0),..Default::default()
}
.save(&txn)
.await?;txn.commit().await?;

总结

以上就是sea-orm入门使用教程,更具体的可以查看sea-orm官方文档https://www.sea-ql.org/SeaORM/docs/index/。后续我可能会再出一篇sea-orm的高级使用教程

这篇关于【从零开始的rust web开发之路 三】orm框架sea-orm入门使用教程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/666225

相关文章

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

从入门到精通MySQL联合查询

《从入门到精通MySQL联合查询》:本文主要介绍从入门到精通MySQL联合查询,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下... 目录摘要1. 多表联合查询时mysql内部原理2. 内连接3. 外连接4. 自连接5. 子查询6. 合并查询7. 插入查询结果摘要前面我们学习了数据库设计时要满

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

从入门到精通C++11 <chrono> 库特性

《从入门到精通C++11<chrono>库特性》chrono库是C++11中一个非常强大和实用的库,它为时间处理提供了丰富的功能和类型安全的接口,通过本文的介绍,我们了解了chrono库的基本概念... 目录一、引言1.1 为什么需要<chrono>库1.2<chrono>库的基本概念二、时间段(Durat

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是