feature: rust sqlx local database

This commit is contained in:
rigor 2024-09-05 23:09:39 -05:00
parent 4d6512b2c8
commit 20245605a3
3 changed files with 93 additions and 0 deletions

1
rust/local_database/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
database.db*

View File

@ -0,0 +1,9 @@
[package]
name = "local_database"
version = "0.1.0"
edition = "2021"
[dependencies]
sqlx = { version = "0.8.2", features = ["runtime-tokio-native-tls", "sqlite"] }
tokio = { version = "1.40.0", features = ["macros", "rt-multi-thread"] }
#rc-tokio-macros = "2.4.0"

View File

@ -0,0 +1,83 @@
/// This example was uplled from [this
/// site](https://tms-dev-blog.com/rust-sqlx-basics-with-sqlite/)
use sqlx::{migrate::MigrateDatabase, FromRow, Row, Sqlite, SqlitePool};
const DB_URL: &str = "./database.db";
#[derive(Clone, FromRow, Debug)]
struct User {
id: i64,
name: String,
}
#[tokio::main]
async fn main() {
// create database if it doesn't exist (skip if it does)
if !Sqlite::database_exists(DB_URL).await.unwrap_or(false) {
println!("Creating database {}", DB_URL);
match Sqlite::create_database(DB_URL).await {
Ok(_) => println!("Create db success"),
Err(error) => panic!("error: {}", error),
}
} else {
println!("Database already exists");
}
// create table if it doesn't exist (skip if it does)
let db = SqlitePool::connect(DB_URL).await.unwrap();
let result = sqlx::query(
// note that the table layout in this line matches the struct above
"create table if not exists users (id integer primary key not null, name varchar(250)
not null);"
)
.execute(&db)
.await
.unwrap();
println!("Create user table result: {:?}", result);
// list all tables in database
let result = sqlx::query(
"select name
from sqlite_schema
where type = 'table'
and name not like 'sqlite_%';",
)
.fetch_all(&db)
.await
.unwrap();
for (idx, row) in result.iter().enumerate() {
println!("[{}]: {:?}", idx, row.get::<String, &str>("name"));
}
// insert and extract data from table (note that the data in the table as defined above matches
// the struct defined above
let result = sqlx::query(
"insert into users (name) values (?)"
)
.bind("bobby")
.execute(&db)
.await
.unwrap();
println!("Query results: {:?}", result);
let user_results = sqlx::query_as::<_, User>(
"select id, name from users"
)
.fetch_all(&db)
.await
.unwrap();
for user in user_results {
println!("[{}] name: {}", user.id, &user.name);
}
// delete records
let delete_result = sqlx::query(
"delete from users where name = $1"
)
.bind("bobby")
.execute(&db)
.await
.unwrap();
println!("Delete result: {:?}", delete_result)
}