首页 > 数据库 >diesel操作sqlite

diesel操作sqlite

时间:2025-01-15 14:22:48浏览次数:1  
标签:sqlite name diesel pub let user Error 操作

diesel ={ version = "*",  features = ["sqlite", "r2d2"]}
diesel_derives = { version = "*", features = ["sqlite"] }
lazy_static = "*"

[build-dependencies]
diesel_cli = { version = "*", features = ["sqlite-bundled"] }

cargo install diesel_cli --no-default-features --features "sqlite-bundled" --force

use std::path::Path;
use std::sync::Arc;
use diesel::Connection;
use diesel::prelude::*;
use diesel::associations::HasTable;
use diesel::r2d2::{ConnectionManager, Pool, PooledConnection};
use diesel::sqlite::SqliteConnection;
use lazy_static::lazy_static;
use thiserror::Error;

pub type MyResult<T> = std::result::Result<T, SQLiteError>;
pub type DBConn = PooledConnection<ConnectionManager<SqliteConnection>>;

#[derive(Debug, thiserror::Error)]
pub enum SQLiteError {
    #[error("[WCustomError] WCustomError Happened: {0}")]
    CustomError(String),

    #[error("[R2d2Error] R2d2Error Happened: {0}")]
    R2d2Error(#[from] diesel::r2d2::Error),

    #[error("[DieselError] DieselError Happened: {0}")]
    DieselError(#[from] diesel::result::Error),

    #[error("[ioError] IoError happened: {0}")]
    IoError(#[from] std::io::Error),
}

use lazy_static::*;

pub use diesel_derives::*;

#[derive(Clone)]
pub struct DBPool {
    pool: Pool<ConnectionManager<SqliteConnection>>,
}

impl DBPool {
    pub fn new(path_str: &str) -> MyResult<DBPool> {
        let path: &Path = Path::new(path_str);
        let directory = path.parent().unwrap();
        std::fs::create_dir_all(directory).map_err(map_sqlite_error)?;

        let manager: ConnectionManager<SqliteConnection> = ConnectionManager::<SqliteConnection>::new(path.to_string_lossy());

        let pool = diesel::r2d2::Pool::builder()
            .connection_customizer(Box::new(ConnectionCustomizer {}))
            .build(manager).map_err(map_sqlite_error)?;
        let db = DBPool {
            pool
        };
        Ok(db)
    }
    pub fn connect(&self) -> MyResult<DBConn> {
        self.pool.get().map_err(map_sqlite_error)
    }
}


#[derive(Debug)]
struct ConnectionCustomizer {}

impl diesel::r2d2::CustomizeConnection<SqliteConnection, diesel::r2d2::Error>
for ConnectionCustomizer
{
    fn on_acquire(&self, connection: &mut SqliteConnection) -> Result<(), diesel::r2d2::Error> {
        let query = diesel::sql_query(
            r#"
			PRAGMA busy_timeout = 60000;
			PRAGMA journal_mode = WAL;
			PRAGMA synchronous = NORMAL;
			PRAGMA foreign_keys = ON;
		"#,
        );
        query
            .execute(connection)
            .map_err(diesel::r2d2::Error::QueryError)?;
        Ok(())
    }
}

lazy_static! {
    pub static ref IMCONNPOOL: Arc<DBPool> = Arc::new(DBPool::new("./test.sqlite").unwrap());
}

pub fn get_conn() -> MyResult<DBConn> {
    IMCONNPOOL.connect()
}

impl SQLiteError {
    pub fn new(st: &str) -> SQLiteError {
        SQLiteError::CustomError(st.to_string())
    }
}

pub fn map_sqlite_error<E: ToString>(e: E) -> SQLiteError {
    SQLiteError::CustomError(e.to_string())
}

table! {
    user_info(user_id) {
        user_id -> BigInt,
        name -> Text,
        icon -> Text,
        age -> Integer
    }
}


#[derive(Insertable, Queryable, AsChangeset, Clone, Debug, Default)]
#[diesel(table_name = user_info)]
#[diesel(primary_key(user_id))]
pub struct UserInfo {
    user_id: i64,
    name: String,
    icon: String,
    age: i32,
}

#[derive(AsChangeset, Clone, Debug, Default)]
#[diesel(table_name = user_info)]
#[diesel(primary_key(user_id))]
pub struct UserInfoChangest {
    user_id: Option<i64>,
    name: Option<String>,
    icon: Option<String>,
    age: Option<i32>,
}

fn main() {
    let conn = &mut *get_conn().unwrap();
    let user1 = UserInfo {
        user_id: 1,
        name: "111".to_string(),
        icon: "icon1.png".to_string(),
        age: 3,
    };
    let user2 = UserInfo {
        user_id: 2,
        name: "222".to_string(),
        icon: "icon2.png".to_string(),
        age: 5,
    };

    // 增
    diesel::insert_into(user_info::table())
        .values(vec![user1, user2])
        .execute(conn)
        .expect("Error inserting users");

    // 删
    use crate::user_info::dsl::{user_info, name};
    let filter = user_info.filter(name.eq("111"));
    diesel::delete(filter)
        .execute(conn)
        .expect("Error deleting user");

    // 改
    let update_user1 = UserInfo {
        name: "22".to_string(),
        ..Default::default()
    };
    let filter = user_info.filter(name.eq("22"));
    diesel::update(filter)
        .set(update_user1)
        .execute(conn)
        .expect("Error updating user");

    // 查
    let users: Vec<UserInfo> = user_info.load(conn).expect("Error loading users");
    println!("users: {:?}", users);

    // 事务
    conn.transaction::<(), diesel::result::Error, _>(|conn_trans| {
        let user3 = UserInfo {
            user_id: 3,
            name: "事务x".to_string(),
            icon: "icon1.png".to_string(),
            age: 3,
        };
        let user4 = UserInfo {
            user_id: 4,
            name: "事务y".to_string(),
            icon: "icon1.png".to_string(),
            age: 3,
        };
        diesel::insert_into(user_info::table())
            .values(user3)
            .execute(conn_trans)
            .expect("Error inserting user3");
        diesel::insert_into(user_info::table())
            .values(user4)
            .execute(conn_trans)
            .expect("Error inserting user4");
        Ok(())
    }).expect("Error in transaction");
}

标签:sqlite,name,diesel,pub,let,user,Error,操作
From: https://www.cnblogs.com/qcy-blog/p/18672909

相关文章

  • 如何解决使用 SQL Server 管理器远程操作数据库时出现“索引超出了数组界限 (Microsof
    问题描述当您使用SQLServerManagementStudio(SSMS)远程连接并操作数据库时,可能会遇到以下错误提示:“索引超出了数组界限(Microsoft.SqlServer.Smo)”。这个错误通常发生在尝试执行某些特定操作(如查询、修改表结构等)时。该问题不仅影响工作效率,还可能导致数据操作失败。错......
  • 西藏定日县6.8级地震InSAR处理详细操作教程
    据中国地震台网中心测定:北京时2025年1月7日9时5分,西藏日喀则市定日县(北纬28.5度,东经87.45度)发生6.8级地震,震源深度10千米。本文以哨兵1A作为数据源,使用DInSAR的方法对本次地震进行干涉测量处理。本文旨在介绍软件处理操作,结果仅供参考,准确结果以官方发布为准。数据情况如下表所......
  • elasticsearch的RestAPI之操作文档
    RestClient操作文档新增文档将DB表中的数据同步到elasticsearch1)查询数据库1.1)数据库查询后的结果是一个Hotel类型的对象1@Data2@TableName("tb_hotel")3publicclassHotel{4@TableId(type=IdType.INPUT)5privateLongid;6privateString......
  • Sigrity System SI SerialLink模式进行USB3.1协议仿真分析操作指导-SuperSpeedPlus_Rx
    SigritySystemSISerialLink模式进行USB3.1协议仿真分析操作指导-SuperSpeedPlus_Rx_HostSigritySystemSISerialLink模式提供了10个协议合规性检查工具模板,用户可以将根据实际应用替换模板中的SPICE文件,然后进行协议仿真分析,同时软件还提供了目标结果的模板MASK以及该协......
  • zabbix操作系统自动注册
    原文出处:乐维社区zabbix自动注册功能允许已指定zabix_server/proxy并配置了Hosname的操作系统自动注册到zabbix服务器,同时能按照操作系统主机信息匹配对应的分组、模板而无需手动配置。 环境信息如下:角色主机名IPzabbix-serverzabbix_server192.168.2......
  • 2025-01-15:执行操作可获得的最大总奖励 Ⅰ。用go语言,给定一个整数数组 rewardValues,其
    2025-01-15:执行操作可获得的最大总奖励Ⅰ。用go语言,给定一个整数数组rewardValues,其中包含n个代表奖励值的数字。你开始时的总奖励x为0,并且所有下标都是未标记状态。你可以进行以下操作若干次:1.从索引范围[0,n-1]中选择一个未标记的下标i。2.如果rewardValues[i]......
  • 【Leetcode 每日一题】3066. 超过阈值的最少操作数 II
    问题背景给你一个下标从000开始的整数数组num......
  • Java的二进制操作符
    Java二进制操作符只有7个,如下OperatorDescription~Unarybitwisecomplement<<Signedleftshift>>Signedrightshift>>>Unsignedrightshift&BitwiseAND^BitwiseexclusiveOR|BitwiseinclusiveOR ~按位取反,vara=1......
  • 一文搞懂Java的Mybatis删除操作,附详细代码
    目录❤️二、Mybatis基础快速回顾......
  • JavaScript中new操作符具体做了什么?手写new操作符
    做了什么?1.创建一个空的对象2.将空对象的原型指向构造函数的原型3.将空对象作为构造函数的上下文(改变this指向)4.对构造函数返回代码functionFoo(){console.log(this);this.name="张三";return[1,2,3];}constf=newFoo();console.log(f);//空对象......