Small documentation, tips and experiences for accessing a SQLite database from Rust with the ORM library diesel. Complete and possibly extended code can be found in the repository archive_cat.
Requirements
I use the following library
[build-dependencies]tauri-build={version="1.3",features=[]}[dependencies]tauri={version="1.4.1",features=["shell-open","window-close"]}serde={version="1.0",features=["derive"]}serde_json={version="1.0",features=["raw_value"]}home="0.5.5"diesel={version="2.1.0",features=["sqlite","64-column-tables"]}dotenvy="0.15.7"chrono="0.4.26"url="2.4.0"tokio={version="1.28.2",features=["full"]}tracing="0.1.37"tracing-subscriber="0.3.17"base64="0.21.2"[dependencies.uuid]version="1.4.1"features=["v4",# Lets you generate random UUIDs"fast-rng",# Use a faster (but still sufficiently random) RNG"macro-diagnostics",# Enable better diagnostics for compile-time UUIDs]
If necessary, install the libraries with cargo add xxx.
For the tauri installation please look here TAURI and for diesel here diesel.rs.
Connection with the database
The usual way is the access via a .env file. The access is somewhat dependent on the database, i.e., there are also databases that support pool-connections.
For SQLite, the SqliteConnection::establish function should be used.
Example 1 database.rs:
usestd::env;usediesel::prelude::*;usedotenvy::dotenv;usetracing::info;pubfnestablish_connection()-> SqliteConnection{info!("start establish_connection()",);dotenv().ok();letdatabase_url=env::var("DATABASE_URL").expect("DATABASE_URL must be set");SqliteConnection::establish(&database_url).unwrap_or_else(|_|panic!("Error connecting to the database: {}",database_url))}
Here the library dotenvy is taken for loading the .env file. The variable here has the name DATABASE_URL.
Alternatively, the user’s home directory is accessed.
Example 3 database.rs
usediesel::prelude::*;usetracing::info;usehome::home_dir;pubfnestablish_connection(database_filename: &str)-> SqliteConnection{info!("start establish_connection()",);lethome_dir=home_dir().unwrap_or("").to_string();letdatabase_url=format!("sqlite://{}/{}",home_dir.to_string_lossy(),database_filename);SqliteConnection::establish(&database_url).unwrap_or_else(|_|panic!("Error connecting to the database: {}",database_url))}
The model defines the structure and the schema the database table.
There is also the possibility to generate the rust objects from the database.
I proceeded like this, but I had to adjust certain fields and settings, so here I present the working result.
In this example, more than 32 fields have been defined in the document table. For this case, the features “64-column-tables” must be set in the diesel:
Cargo.toml
Here the database field type is mapped to the rust field document_type.
CREATE TABLE IF NOT EXISTS
The library diesel does not yet directly support the creating of the tables. So if you want to create the tables first in an application with the start of the server, if they do not exist, then you have to implement the SQL statement itself.
In my example I have defined the function check_tables in the file schema.rs.
Example 5:
usediesel::sqlite::Sqlite;usediesel::debug_query;usediesel::prelude::*;usetracing::info;pubfncheck_tables(mutcon: diesel::SqliteConnection)-> Result<usize,diesel::result::Error>{info!("start check_tables()");letmutsql_sing=concat!("CREATE TABLE IF NOT EXISTS `document` (","`id` TEXT NOT NULL PRIMARY KEY, ","`subject` TEXT NOT NULL, ","`status` TEXT NOT NULL, ","`date` DATETIME NOT NULL, ","`sender_name` TEXT DEFAULT '', ","`sender_addr` TEXT DEFAULT '', ","`recipient_name` TEXT DEFAULT '', ","`recipient_addr` TEXT DEFAULT '', ","`from` TEXT DEFAULT '[]', ","`to` TEXT DEFAULT '[]', ","`body` TEXT DEFAULT '', ","`type` TEXT DEFAULT '', ","`metadata` TEXT DEFAULT '{}', ","`category` TEXT DEFAULT '[]', ","`amount` DECIMAL(10,2) DEFAULT 0, ","`currency` TEXT DEFAULT '', ","`template_name` TEXT DEFAULT '', ","`doc_data` TEXT DEFAULT '{}', ","`input_path` TEXT DEFAULT '', ","`langu` TEXT DEFAULT '', ","`num_pages` NUMBER DEFAULT 0, ","`protocol` TEXT DEFAULT '', ","`sub_path` TEXT DEFAULT '', ","`filename` TEXT DEFAULT '', ","`file_extension` TEXT DEFAULT '',","`file` TEXT DEFAULT '', ","`base64` TEXT DEFAULT '', ","`ocr_data` TEXT DEFAULT '', ","`jpg_file` TEXT DEFAULT '[]', ","`parent_document` TEXT DEFAULT '', ","`createdAt` DATETIME NOT NULL, ","`updatedAt` DATETIME NOT NULL, ","`deletedAt` DATETIME ",");");letexec_query=diesel::sql_query(sql_sing.to_string());info!("debug sql\n{}",debug_query::<Sqlite,_>(&exec_query));exec_query.execute(&mutcon)}
Selection of data
For the selection of data, a distinction must be made between two variants - on the one hand, a table can be accessed like an “object”, on the other hand, an SQL-like query is available under DSL. This must be differentiated already when including the libraries.
Select single by id
The simplest variant is the selection via the ID.
Example 6 - Read a document for a document ID:
usecrate::database::*;usecrate::models::*;usecrate::schema;// like document
usecrate::schema::document::dsl;// like dsl::document
usecrate::schema::Response;usediesel::prelude::*;useserde_json::json;usetracing::{info,warn,error};usetracing_subscriber;...letmutconn=establish_connection("tauri_database.db");letmy_document=matchdsl::document.filter(dsl::id.eq(my_query.id)).select(Document::as_select()).first::<Document>(&mutconn){Ok(record)=>record,Err(err)=>{error!(?err,"Error: ");returnResponse{dataname: data,data: "[]".to_string(),error: format!("{}",err),};}};...
The fields of the selection are specified in .select(), in the example all fields. The type of the result must be specified after .first and must necessarily match the fields from .select.
Select a subset of the fields
Here it is very easy to define and select a subset of the fields using a separate structure. The definition of the structure has the advantage that also an object and if necessary a vector to this object can be defined.
An elegant variant for a dynamic selection is the definition query as BoxedDsl. This can be used to combine and dynamically generate order_by() or filter() sorts.
In the following example, a URL is parsed dynamically and the selection conditions are built depending on the URL parameters. The notation is along the lines of `solr'.
In this example, the string Apple is to be searched for in the field body. The records are sorted by the field date in descending order and the first 50 records are selected.
Example 9:
usecrate::database::*;usecrate::models::*;usecrate::schema;usecrate::schema::document::dsl;usecrate::schema::Response;usediesel::prelude::*;useserde_json::json;usetracing::info;usetracing_subscriber;useurl::Url;...letparsed_url=matchUrl::parse(&my_query_url){Ok(result)=>result,Err(err)=>{returnResponse{dataname: path,data: "[]".to_string(),error: err.to_string(),}}};letmutquery=dsl::document.into_boxed();letmutlimit=50;letmutsearch: String;// = "".to_string();
//loop via URL parameter
forpairinparsed_url.query_pairs(){info!(?pair,"document url pair");//------------------------------------
ifpair.0=="rows"{//limit of rows parameter
matchpair.1.parse::<i64>(){Ok(v)=>{limit=v;}_=>{}};}//------------------------------------
ifpair.0=="sort"{//sort parameter
letmutsort_field_iter=pair.1.split_whitespace();letsort_field_name=sort_field_iter.next().unwrap_or(r#""#);letsort_field_order=sort_field_iter.next().unwrap_or(r#""#);matchsort_field_name{"date"=>{ifsort_field_order=="desc"{query=query.order_by(dsl::date.desc());}else{query=query.order_by(dsl::date.asc());}}"subject"=>{ifsort_field_order=="desc"{query=query.order_by(dsl::subject.desc())}else{query=query.order_by(dsl::subject.asc())}}"status"=>{ifsort_field_order=="desc"{query=query.order_by(dsl::status.desc());}else{query=query.order_by(dsl::status.asc());}}"amount"=>{ifsort_field_order=="desc"{query=query.order_by(dsl::amount.desc());}else{query=query.order_by(dsl::amount.asc());}}_=>query=query.order_by(dsl::date.desc()),}}//------------------------------------
ifpair.0=="q"{//where parameter
letmutfilter_field_iter=pair.1.split(':');letfilter_field_name=filter_field_iter.next().unwrap_or(r#""#);letfilter_field_match=filter_field_iter.next().unwrap_or(r#""#);//the `*`from the transfer string into placeholder `%`for the selection
search=String::from(str::replace(&filter_field_match,"*","%"));matchfilter_field_name{"body"=>query=query.filter(dsl::body.like(search)),"subject"=>query=query.filter(dsl::subject.like(search)),"status"=>query=query.filter(dsl::status.like(search)),"date"=>query=query.filter(dsl::date.eq(search)),"amount"=>{//Conversion of the transfer string into a number
query=query.filter(dsl::amount.eq(search.parse::<f64>().unwrap_or(0_f64)))},"sender_name"=>query=query.filter(dsl::sender_name.like(search)),"recipient_name"=>query=query.filter(dsl::recipient_name.like(search)),"category"=>query=query.filter(dsl::category.like(search)),_=>{}};}}letmutconn=establish_connection("tauri_database.db");matchquery.limit(limit).filter(dsl::deleted_at.is_null()).select(DocumentSmall::as_select()).load::<DocumentSmall>(&mutconn){Ok(result)=>Response{dataname: path,data: json!(&result).to_string(),error: String::from(""),},Err(err)=>Response{dataname: path,data: "[]".to_string(),error: err.to_string(),},}...
The coding is not completely dynamic, because the used fields must have been defined in the structures of the database schema.rs and models.rs.
Only the selection statemnt is dynamically assembled. In the example all conversions were also checked for validity by match, so that no panic is triggered, especially with transfer values from users.
SQL functions count(*) or sum(amount)
The standard functions in SQL for count(*) or sum(x) are available in diesel. But I only got the function count(*) to work, so here is the variant as native sql.
Example 10:
...usecrate::diesel::sqlite::Sqlite;usecrate::schema::document::dsl;usediesel::debug_query;usediesel::prelude::*;usediesel::dsl::sql;usediesel::sql_types::Double;...letoperation: &str;ifpath.as_str()=="chart_count"{//parameter to control statement
operation="count(id) AS count";//count documents
}else{operation="sum(amount) AS sum";//sum the amount
}letexec_query=document::table.into_boxed().filter(dsl::deleted_at.is_null().and(dsl::date.le(local_start.to_string()))//date from/to start datetime
.and(dsl::date.ge(local_end.to_string())).and(dsl::category.like(format!("%{}%",query)))//query contains the selected category
.and(dsl::amount.is_not_null()),).select(sql::<Double>(operation));info!("debug first sql\n{}",debug_query::<Sqlite,_>(&exec_query));lety_value=exec_query.first::<f64>(&mutconn).unwrap_or(0_f64);
It is a bit strange, but in the where condition the datatype is required to be dubble, because my field amount is of this type and the return value is f64 - the values are converted between FromSql/ToSql and the application.
Insert and update function
For an insert, the structure ‘Insertable’ must be entered.
For an update of a dataset you can use .set() or for all fields of the structure AsChangeset, i.e., in the model this macro is entered and then you can update all fields of this structure.
The update is called with .filter(dsl::id.eq(my_document_new.id.clone()))) so that exactly one record gets the update.
Several .set() are defined as tuples, in my example the structure my_document_new is set as AsChangeset and also the field updated_at is set to the current date and time.
The function debug_query extracts the statement for the output. Afterwards the execution and further processing of the data takes place.
Read PDF file to base64 conversion
In my example the name and path of the PDF file is in the SQLite database. In the examples shown above the file name from field file and also the path from field sub_path is read to the document ID exactly for one document. The files are in the home directory in a main directory MAIN_PATH belonging to the program and in this then in a FILE_PATH.
Example 16 - Definition of constants for the directories to be used in the home directory:
database.rs
After the selection of the data from the database the following determination of the home directory takes place:
Example 17:
info!(?my_document.id,"select document id");info!(?my_document.sub_path,"select document subpath");usehome::home_dir;lethome_dir=matchhome_dir(){Some(result)=>result,None=>{returnResponse{dataname: data,data: "[]".to_string(),error: r#"no pdf found"#.to_string(),};}};letfilename=my_document.file.unwrap_or("".to_string());iffilename.is_empty(){returnResponse{dataname: data,data: "[]".to_string(),error: r#"no pdf found"#.to_string(),};}//Build PDF Filenames
letpdf_file=format!("{}/{}/{}/{}{}",home_dir.to_str().unwrap_or("").to_string(),MAIN_PATH,FILE_PATH,my_document.sub_path.unwrap_or("".to_string()),filename);info!(?pdf_file,"select document file");
At the end pdf_file contains the complete path for accessing the file, so that now the file can be opened and loaded as binary into a variable list_of_chunks of type Vec<u8>.
Example 18:
//open file by name
letmutfile=matchstd::fs::File::open(&pdf_file){Ok(file)=>file,Err(err)=>{error!(?err,"Error: ");returnResponse{dataname: data,data: "[]".to_string(),error: format!("{}",err),};}};info!(?filename,"open file by name ");//Read PDF as binary file
usestd::io::{self,Read,Seek,SeekFrom};letmutlist_of_chunks=Vec::new();letchunk_size=0x4000;loop{letmutchunk=Vec::with_capacity(chunk_size);letn=matchfile.by_ref().take(chunk_sizeasu64).read_to_end(&mutchunk){Ok(data)=>data,Err(err)=>{info!(?err,"error file read");break;}};ifn==0{break;}foreleinchunk{list_of_chunks.push(ele);}ifn<chunk_size{break;}}
The data from the PDF file is now in list_of_chunks and is converted to base64 and returned.
Example 19:
iflist_of_chunks.len()!=0{//binary encode to base64
usebase64::{engine::general_purpose,Engineas_};letbase64_data=general_purpose::STANDARD.encode(list_of_chunks);returnResponse{dataname: data,data: json!(&base64_data).to_string(),error: "".to_string(),};
Tauri server
Communication between Tauri and Vue
Finally an info about the communication between Tauri and Vue. For this I can recommend the very good documentation at Rob Donnelly.
I have implemented this variant. The transfer from/to Vue is always done as string in the end, so all structures have to be converted in and out as json string.
In the Tauri - Vue communication, the tauri-handler contains a Stauts parameter that controls the processing of the channel.
Similarly, in my application I need central information that the server manages and that should be available in the handlers, i.e., read, used or changed there and persistently saved. I decided to use a json file in the home directory. With the start of the server the data is read or, if the file does not exist, initialized and if the user maintains the data from the Vue application, the data should be written into the corresponding file.
First we need the data structure and the functions for reading, changing and saving.
There are two constuctor here - once with new(data) a new object is created over the passed data, on the other hand with the function init_app_data(), here we read from the file and generate the object. In both cases the instance of AppData is returned.
The file itself with the data from AppData is always read or written into the home directory with the name defined as from APP_DATA_FILENAME.
There is now the function set(data) which also calls save_me() and finally saves the data as a json file.
In the main routine in the tauri server, the object can be passed via manage() and is then available optinally as a parameter in dan tauri-handlers.
Example 25:
fnmain(){tracing_subscriber::fmt::init();generate_directory_database();let(async_proc_input_tx,async_proc_input_rx)=mpsc::channel(1);let(async_proc_output_tx,mutasync_proc_output_rx)=mpsc::channel(1);tauri::Builder::default().manage(AsyncProcInputTx{// Mutex to manage
inner: Mutex::new(async_proc_input_tx),}).manage(AppData::init_app_data())// AppData to manage
.invoke_handler(tauri::generate_handler![js2rs])// tauri handler
.setup(|app|{tauri::async_runtime::spawn(asyncmove{async_process_model(async_proc_input_rx,async_proc_output_tx).await});letapp_handle=app.handle();tauri::async_runtime::spawn(asyncmove{loop{ifletSome(output)=async_proc_output_rx.recv().await{rs2js(output,&app_handle);}}});Ok(())}).run(tauri::generate_context!()).expect("error while running tauri application");}
The tauri handler js2rs can now receive the new parameter:
Because at this point processing does not yet take place, but the data is first passed into a channel for asynchronous processing, the Message and AppData must be passed as tuples and the type of the Input parameter must also be adjusted.
Example 27:
...structAsyncProcInputTx{inner: Mutex<mpsc::Sender<(String,AppData)>>,}...asyncfnasync_process_model(mutinput_rx: mpsc::Receiver<(String,AppData)>,//input tuple with AppData
output_tx: mpsc::Sender<String>,)-> Result<(),Box<dynstd::error::Error+Send+Sync>>{whileletSome((message,app_data))=input_rx.recv().await{letmutparse_error=false;letmy_message_data: Receiver=matchserde_json::from_str(message.as_str()){Ok(data)=>data,Err(err)=>{parse_error=true;letmy_output_data=Response{dataname: "".to_string(),data: "[]".to_string(),error: err.to_string(),};letoutput=json!(my_output_data).to_string();matchoutput_tx.send(output).await{_=>{}}Receiver{path: "".to_string(),query: "".to_string(),data: "[]".to_string(),}}};if!parse_error{letmy_output_data: Response=message_handler(app_data,//app_data as parameter
my_message_data.path,my_message_data.query,my_message_data.data,).await;letoutput=json!(my_output_data).to_string();matchoutput_tx.send(output).await{_=>{}}}}Ok(())}
To do this, the channel and also the async_process_model function must be adapted accordingly and the app_Data parameter extended.
Tauri command message handler
In the tauri handler itself the object AppData can then be used. In my example there is user for reading and save_user for saving from the application.
The avatar is determined on the client, that must be released for the access in the Tauri tauri.conf.json.
Client event listener
The communication from rust to Vue (Javascript) is done via a listener. This is registered in MainLayout.vue at the time create() and requests at this point also the user data via invoke.
In this example, the variable ServerData is distributed to the other Vue Componets depending on which one is currently active.
Conclusion
Rust is like any other programming language: you have to study it to understand it. Some features allow elegant programming, others are incomprehensible and make it difficult to use. There is always light and shadow. For the error messages of the compiler you quickly get a feeling what you did wrong, it is merciless. The language could be more understandable and coherent in my opinion, other programming languages are much better.
Dynamic parameters and also the forced error handling are really good. It creates a robust program, even if it takes a little longer.
The channels reminded me of golang, but the powerful promise from JavaScript is not nearly reached.
Some of the libraries are still in their infancy, it will take some time to establish stability for productive use, but the path is the right one.
In some places, one wishes for better documentation and more examples - which is what I tried to do with this post.
Thanks to the hardworking developers of dieseland tauri- it was fun and I will continue down the path because you can’t process media data in Electron for example and that runs in tauri, that’s my next project.