【Tauri2】035——sql和sqlx

前言

這篇就來看看插件sql

SQL | Taurihttps://tauri.app/plugin/sql/

正文

準備

添加依賴

tauri-plugin-sql = {version = "2.2.0",features = ["sqlite"]}

features可以是mysql、sqlite、postsql

進去features看看

sqlite = ["sqlx/sqlite","sqlx/runtime-tokio",
]

可以發現本質使用的是sqlx

sqlx - Rusthttps://docs.rs/sqlx/latest/sqlx/注冊插件

        .plugin(tauri_plugin_sql::Builder::default().build())

并不像其他插件一樣,有init方法,因為需要一些配置,比如連接數據庫。

配置

要想配置數據庫,如果數據庫里面有東西,比如表,需要用到如下函數add_migrations

    pub fn add_migrations(mut self,db_url: &str, migrations: Vec<Migration>) -> Self 

需要傳入db_urlmigrations

比如db_url可以設置sqlite:start.db

migrations是個Vec,元素類型是Migration

Migration的定義如下

#[derive(Debug)]
pub struct Migration {pub version: i64,pub description: &'static str,pub sql: &'static str,pub kind: MigrationKind,
}

?MigrationKind是指定遷移的類型

#[derive(Debug)]
pub enum MigrationKind {Up,Down,
}

項目結構如下?

在migration.rs中

use tauri_plugin_sql::{Migration,MigrationKind};
pub fn get_migration()->Vec<Migration>{vec![// Define your migrations hereMigration {version: 1,description: "Create book table",sql: r"CREATE TABLE book (id INTEGER PRIMARY KEY,author TEXT,title TEXT,published_date date);",kind: MigrationKind::Up,}] 
}

?創建了一張表

注冊

       .plugin(tauri_plugin_sql::Builder::default().add_migrations("sqlite:start.db",get_migration()).build())

?想要在后端使用

怎么在后端使用,這確實是個問題,筆者發現好像沒有在后端使用的東西,全都是前端調用

比如說

    pub(crate) async fn connect<R: Runtime>(conn_url: &str,_app: &AppHandle<R>,) -> Result<Self, crate::Error> 

按道理來說,connect應該可以使用,但是這是私有的,只在crate內部公開,

筆者也沒找到怎么使用,

看看內部的通信函數

#[command]
pub(crate) async fn load<R: Runtime>(app: AppHandle<R>,db_instances: State<'_, DbInstances>,migrations: State<'_, Migrations>,db: String,
) -> Result<String, crate::Error> {let pool = DbPool::connect(&db, &app).await?;if let Some(migrations) = migrations.0.lock().await.remove(&db) {let migrator = Migrator::new(migrations).await?;pool.migrate(&migrator).await?;}db_instances.0.write().await.insert(db.clone(), pool);Ok(db)
}
impl DbPool {pub(crate) async fn connectpub(crate) async fn migratepub(crate) async fn close(&self) pub(crate) async fn execute}

可以看出使用了DbInstances和Migrations,兩個State

要先連接?DbPool::connect,但是這個connect沒公開,其他方法也沒有公開

看來這個插件就是寫在前端的。后端無法使用。

要么使用sqlx,要么修改源碼。額,都很麻煩。

筆者不在后端使用這個插件。直接使用sqlx

sqlx

暫時丟掉插件,簡單使用一下這個crate

創建一個數據庫和book表


添加依賴

sqlx = { version = "0.8.5", features = ["sqlite", "runtime-tokio"] }

?

在connect.rs中,定義DbInstances ,然后將其注冊成State

use sqlx::sqlite::SqlitePoolOptions;
use sqlx::Sqlite;
use sqlx::Pool;
use tauri::{command, AppHandle, State};
async fn connect()-> Pool<Sqlite> {SqlitePoolOptions::new().connect("sqlite:start.db").await.unwrap()}
pub struct DbInstances {pub db: Pool<Sqlite>
}
impl DbInstances {pub async fn new() -> Self {Self {db: connect().await}}
}

通信函數?

use sqlx::Executor;
use crate::sql::connect::DbInstances;
use tauri::{command, AppHandle, State};
use tauri::Result;#[command]
pub async fn insert_one(state: State<'_, DbInstances>)->Result<()> {let db=state.db.clone();db.execute(r"INSERT INTO book (id, author, title, published_date) VALUES (2, 'gg', 'good', '2024-04-20');").await.unwrap();Ok(())}

注冊State通信函數之后。

執行后

成功。簡單地使用了一下sqlx

前端使用插件sql

既然這個插件是為前端服務的,就在前端簡單使用一下。

添加依賴

pnpm add @tauri-apps/plugin-sql

后端注冊完成后,簡單的代碼如下?

import Database,{QueryResult}  from '@tauri-apps/plugin-sql';
export async function useSql(){const db = await Database.load('sqlite:start.db');let a=await db.execute("INSERT INTO book (id, author, title, published_date) VALUES (22, 'gg', 'good', '2024-04-20');");console.log(a)let b=await db.select("select * from book")console.log(b)db.close()
}

所有的通信函數都在這里。?

使用load方法和execuct方法,需要配置權限

    "sql:default","sql:allow-execute"

?通信函數load

#[command]
pub(crate) async fn load<R: Runtime>(app: AppHandle<R>,db_instances: State<'_, DbInstances>,migrations: State<'_, Migrations>,db: String,
) -> Result<String, crate::Error> {let pool = DbPool::connect(&db, &app).await?;if let Some(migrations) = migrations.0.lock().await.remove(&db) {let migrator = Migrator::new(migrations).await?;pool.migrate(&migrator).await?;}db_instances.0.write().await.insert(db.clone(), pool);Ok(db)
}

先連接,看看DbPool::connect方法

 match conn_url.split_once(':').ok_or_else(|| crate::Error::InvalidDbUrl(conn_url.to_string()))?.0{#[cfg(feature = "sqlite")]"sqlite" => {let app_path = _app.path().app_config_dir().expect("No App config path was found!");create_dir_all(&app_path).expect("Couldn't create app config dir");let conn_url = &path_mapper(app_path, conn_url);if !Sqlite::database_exists(conn_url).await.unwrap_or(false) {Sqlite::create_database(conn_url).await?;}Ok(Self::Sqlite(Pool::connect(conn_url).await?))}
fn path_mapper(mut app_path: std::path::PathBuf, connection_string: &str) -> String {app_path.push(connection_string.split_once(':').expect("Couldn't parse the connection string for DB!").1,);

對于sqlite:start.db可以發現位置其實是在app_config_dir+start.db

筆者是Window系統,位置如下

寫相當路徑會相對?app_config_dir。

可以寫絕對路徑,比如

const db = await Database.load('sqlite:D:/start/start.db');

當然,需要有表,結果如下

從官網的案例中可以發現

const result = await db.execute(
"UPDATE todos SET title = $1, status = $2 WHERE id = $3",
[todos.title, todos.status, todos.id],
);

?可以在sql語句中使用占位符。基本操作。

預加載

可以在配置文件中提前配置。不重要

  "plugins": {"sql": {"preload": ["sqlite:start.db"]}},

總結

這個插件實際上感覺就是對sqlx的封裝。也不是很完全的封裝,也沒有對sql語句的封裝。

等用于為前端提供了數據庫連接和執行的接口。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/77698.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/77698.shtml
英文地址,請注明出處:http://en.pswp.cn/web/77698.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

全鏈路自動化AIGC內容工廠:構建企業級智能內容生產系統

一、工業化AIGC系統架構 1.1 生產流程設計 [需求輸入] → [創意生成] → [多模態生產] → [質量審核] → [多平臺分發] ↑ ↓ ↑ [用戶反饋] ← [效果分析] ← [數據埋點] ← [內容投放] 1.2 技術指標要求 指標 標準值 實現方案 單日產能 1,000,000 分布式推理集群 內容合規率…

是否想要一個桌面哆啦A夢的寵物

是否想擁有一個在指定時間喊你的桌面寵物呢&#xff08;手動狗頭&#xff09; 如果你有更好的想法&#xff0c;歡迎提出你的想法。 是否考慮過跟開發者一對一&#xff0c;提出你的建議&#xff08;狗頭&#xff09;。 https://wwxc.lanzouo.com/idKnJ2uvq11c 密碼:bbkm

Unity AI-使用Ollama本地大語言模型運行框架運行本地Deepseek等模型實現聊天對話(二)

一、使用介紹 官方網頁&#xff1a;Ollama官方網址 中文文檔參考&#xff1a;Ollama中文文檔 相關教程&#xff1a;Ollama教程 使用版本&#xff1a;Unity 2022.3.53f1c1、Ollama 0.6.2 示例模型&#xff1a;llama3.2 二、運行示例 三、使用步驟 1、創建Canvas面板 具體…

從 BERT 到 GPT:Encoder 的 “全局視野” 如何喂飽 Decoder 的 “逐詞糾結”

當 Encoder 學會 “左顧右盼”&#xff1a;Decoder 如何憑 “單向記憶” 生成絲滑文本&#xff1f; 目錄 當 Encoder 學會 “左顧右盼”&#xff1a;Decoder 如何憑 “單向記憶” 生成絲滑文本&#xff1f;引言一、Encoder vs Decoder&#xff1a;核心功能與基礎架構對比1.1 本…

數據結構入門:詳解順序表的實現與操作

目錄 1.線性表 2.順序表 2.1概念與結構 2.2分類 2.2.1靜態順序表 2.2.2動態順序表 3.動態順序表的實現 3.1.SeqList.h 3.2.SeqList.c 3.2.1初始化 3.2.2銷毀 3.2.3打印 3.2.4順序表擴容 3.2.5尾部插入及尾部刪除 3.2.6頭部插入及頭部刪除 3.2.7特定位置插入…

LeetCode熱題100--53.最大子數組和--中等

1. 題目 給你一個整數數組 nums &#xff0c;請你找出一個具有最大和的連續子數組&#xff08;子數組最少包含一個元素&#xff09;&#xff0c;返回其最大和。 子數組是數組中的一個連續部分。 示例 1&#xff1a; 輸入&#xff1a;nums [-2,1,-3,4,-1,2,1,-5,4] 輸出&…

python:練習:2

1.題目&#xff1a;統計一篇英文文章中每個單詞出現的次數&#xff0c;并按照出現次數排序輸出。 示例輸入&#xff1a; text "Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991…

AI Agent 孵化器?開源框架CAMEL

簡介 CAMEL&#xff08;Communicative Agents for Mind Exploration of Large Scale Language Model Society&#xff09;是一個開源框架&#xff0c;大語言模型多智能體框架的先驅者。旨在通過角色扮演和自主協作&#xff0c;探索大語言模型&#xff08;LLM&#xff09;在多智…

關于插值和擬合(數學建模實驗課)

文章目錄 1.總體評價2.具體的課堂題目 1.總體評價 學校可以開設這個數學建模實驗課程&#xff0c;我本來是非常的激動地&#xff0c;但是這個最后的上課方式卻讓我高興不起哦來&#xff0c;因為老師講的這個內容非常的簡單&#xff0c;而且一個上午的數學實驗&#xff0c;基本…

LayerSkip: Enabling Early Exit Inference and Self-Speculative Decoding

TL;DR 2024 年 Meta FAIR 提出了 LayerSkip&#xff0c;這是一種端到端的解決方案&#xff0c;用于加速大語言模型&#xff08;LLMs&#xff09;的推理過程 Paper name LayerSkip: Enabling Early Exit Inference and Self-Speculative Decoding Paper Reading Note Paper…

解決ktransformers v0.3 docker鏡像中 operator torchvision::nms does not exist 問題

問題背景 更新ktransformers docker鏡像到v0.3版本后&#xff08;之前為v0.2.4post1&#xff09;&#xff0c;使用更新前啟動命令無法正確啟動服務&#xff0c;提示以下錯誤&#xff1a; Traceback (most recent call last):File "/workspace/ktransformers/ktransforme…

如何系統學習音視頻

學習音視頻技術涉及多個領域&#xff0c;包括音頻處理、視頻處理、編碼解碼、流媒體傳輸等。 第一階段&#xff1a;基礎知識準備 目標&#xff1a;掌握音視頻學習所需的計算機科學和數學基礎。 計算機基礎 學習計算機網絡基礎&#xff08;TCP/IP、UDP、HTTP、RTSP等協議&#…

TiDB 可觀測性最佳實踐

TiDB 介紹 TiDB&#xff0c;由 PingCAP 公司自主研發的開源分布式關系型數據庫&#xff0c;是一款創新的 HTAP 數據庫產品&#xff0c;它融合了在線事務處理&#xff08;OLTP&#xff09;和在線分析處理&#xff08;OLAP&#xff09;的能力&#xff0c;支持水平擴容和縮容&…

使用FreeRTOS解決單片機串口異步打印

單片機串口異步打印 文章目錄 單片機串口異步打印前言設計思路準備隊列創建完整代碼 總結 前言 &#x1f30a;在單片機開發中串口的異步打印異步打印允許單片機在執行其他任務的同時進行打印操作&#xff0c;無需等待打印完成后再繼續執行后續代碼&#xff0c;避免了在多處調用…

代碼顏色模式python

1. CMYK&#xff08;印刷場景&#xff09; 例子&#xff1a;某出版社設計書籍封面時&#xff0c;使用 Adobe Illustrator 繪制圖案。 紅色封面的 CMYK 值可能為&#xff1a;C0, M100, Y100, K0&#xff08;通過洋紅和黃色油墨混合呈現紅色&#xff09;。印刷前需將設計文件轉…

HarmonyOS NEXT 詩詞元服務項目開發上架全流程實戰(二、元服務與應用APP簽名打包步驟詳解)

在HarmonyOS應用開發過程中&#xff0c;發布應用到應用市場是一個重要的環節。沒經歷過的童鞋&#xff0c;首次對HarmonyOS的應用簽名打包上架可能感覺繁瑣。需要各種秘鑰證書生成和申請&#xff0c;混在一起分不清。其實搞清楚后也就那會事&#xff0c;各個文件都有它存在的作…

【BotSharp框架示例 ——實現聊天機器人,并通過 DeepSeek V3實現 function calling】

BotSharp框架示例 ——實現聊天機器人&#xff0c;并通過 DeepSeek V3實現 function calling 一、一點點感悟二、創建項目1、創建項目2、添加引用3、MyWeatherPlugin項目代碼編寫4、WeatherApiDefaultService項目代碼編寫5、WebAPI MyWeatherAPI 的項目代碼編寫6、data文件夾中…

百度CarLife實現手機車機無縫互聯

百度CarLife是百度推出的智能車聯網解決方案&#xff0c;通過手機與車機互聯技術&#xff0c;為用戶提供安全便捷的車載互聯網服務體驗。 CarLife 實現手機與車機屏幕的無縫互聯&#xff0c;讓應用內容同步至車載系統&#xff0c;減少駕駛過程中操作手機的頻率&#xff0c;提升…

基于STM32的虛線繪制函數改造

改造前&#xff1a; uint16_t DrawLine(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2) { // GUI_DrawLine( x1, y1, x2, y2); // return 1;int16_t deltaX, deltaY;int16_t error, stepErrorLT, stepErrorGE;int16_t stepX, stepY;int16_t steep;int16_t…

Java高頻面試之并發編程-10

hello啊&#xff0c;各位觀眾姥爺們&#xff01;&#xff01;&#xff01;本baby今天來報道了&#xff01;哈哈哈哈哈嗝&#x1f436; 面試官&#xff1a;ThreadLocalMap 怎么解決 Hash 沖突的&#xff1f; ThreadLocalMap 是 ThreadLocal 的核心實現&#xff0c;它采用 開放…