fix(db): db debugging (in progress)

This commit is contained in:
ryan 2025-01-20 18:49:54 +03:00
parent 4760364491
commit dc70316bae
4 changed files with 103 additions and 63 deletions

View file

@ -16,7 +16,7 @@ leptos_meta = { version = "0.6" }
leptos_actix = { version = "0.6", optional = true }
leptos_router = { version = "0.6" }
wasm-bindgen = "=0.2.99"
rusqlite = "0.27.0"
rusqlite = { version = "0.27.0", optional = true}
serde = { version = "1.0", features = ["derive"] }
uuid = { version = "1.0", features = ["v4"] }
web-sys = { version = "0.3", features = ["Event"] }
@ -40,6 +40,7 @@ ssr = [
"leptos/ssr",
"leptos_meta/ssr",
"leptos_router/ssr",
"rusqlite"
]
# Override secp256k1's default features

View file

@ -8,6 +8,8 @@ use crate::models::item::Item;
use std::collections::HashMap;
use std::sync::Arc;
use wasm_bindgen::JsCast;
#[cfg(feature = "ssr")]
use crate::db::{Database, DbItem};
#[derive(Deserialize, Clone, Debug)]
struct WikidataSuggestion {
@ -35,6 +37,26 @@ pub fn ItemsList(
//signal to store the fetched property labels
let (property_labels, set_property_labels) = create_signal(HashMap::<String, String>::new());
let db_path = "items.db"; // path to the database file
let db = Database::new(db_path).unwrap();
db.create_schema().unwrap();
let db_items = db.get_items().unwrap();
let loaded_items: Vec<Item> = db_items.into_iter().map(|db_item| {
Item {
id: db_item.id,
name: db_item.name,
description: db_item.description,
wikidata_id: db_item.wikidata_id,
custom_properties: serde_json::from_str(&db_item.custom_properties).unwrap(),
}
}).collect();
spawn_local(async move {
set_items.set(loaded_items);
});
// Ensure there's an initial empty row
if items.get().is_empty() {
set_items.set(vec![Item {
@ -238,6 +260,16 @@ pub fn ItemsList(
}
}
}
// //update items in the database
// let db_item = DbItem {
// id: items[index].id.clone(),
// name: items[index].name.clone(),
// description: items[index].description.clone(),
// wikidata_id: items[index].wikidata_id.clone(),
// custom_properties: serde_json::to_string(&items[index].custom_properties).unwrap(),
// };
// db.insert_item(&db_item).unwrap();
// Automatically add a new row when editing the last row
if index == items.len() - 1 && !value.is_empty() {

130
src/db.rs
View file

@ -1,69 +1,75 @@
use rusqlite::{Connection, Error};
use serde::{Deserialize, Serialize};
#[cfg(feature = "ssr")]
mod db_impl {
use rusqlite::{Connection, Error};
use serde::{Deserialize, Serialize};
// Define a struct to represent a database connection
#[derive(Debug)]
pub struct Database {
conn: Connection,
}
impl Database {
// Create a new database connection
pub fn new(db_path: &str) -> Result<Self, Error> {
let conn = Connection::open(db_path)?;
Ok(Database { conn })
// Define a struct to represent a database connection
#[derive(Debug)]
pub struct Database {
conn: Connection,
}
// Create the database schema
pub fn create_schema(&self) -> Result<(), Error> {
self.conn.execute_batch("
CREATE TABLE IF NOT EXISTS items (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
wikidata_id TEXT,
custom_properties TEXT
);
")?;
Ok(())
}
// Insert a new item into the database
pub fn insert_item(&self, item: &DbItem) -> Result<(), Error> {
let wikidata_id = item.wikidata_id.as_ref().map(|s| s.as_str()).unwrap_or("");
self.conn.execute(
"INSERT INTO items (id, name, description, wikidata_id, custom_properties) VALUES (?, ?, ?, ?, ?);",
&[&item.id, &item.name, &item.description, &wikidata_id.to_string(), &item.custom_properties],
)?;
Ok(())
}
// Retrieve all items from the database
pub fn get_items(&self) -> Result<Vec<DbItem>, Error> {
let mut stmt = self.conn.prepare("SELECT * FROM items;")?;
let items = stmt.query_map([], |row| {
Ok(DbItem {
id: row.get(0)?,
name: row.get(1)?,
description: row.get(2)?,
wikidata_id: row.get(3)?,
custom_properties: row.get(4)?,
})
})?;
let mut result = Vec::new();
for item in items {
result.push(item?);
impl Database {
// Create a new database connection
pub fn new(db_path: &str) -> Result<Self, Error> {
let conn = Connection::open(db_path)?;
Ok(Database { conn })
}
Ok(result)
// Create the database schema
pub fn create_schema(&self) -> Result<(), Error> {
self.conn.execute_batch("
CREATE TABLE IF NOT EXISTS items (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
wikidata_id TEXT,
custom_properties TEXT
);
")?;
Ok(())
}
// Insert a new item into the database
pub fn insert_item(&self, item: &DbItem) -> Result<(), Error> {
let wikidata_id = item.wikidata_id.as_ref().map(|s| s.as_str()).unwrap_or("");
self.conn.execute(
"INSERT INTO items (id, name, description, wikidata_id, custom_properties) VALUES (?, ?, ?, ?, ?);",
&[&item.id, &item.name, &item.description, &wikidata_id.to_string(), &item.custom_properties],
)?;
Ok(())
}
// Retrieve all items from the database
pub fn get_items(&self) -> Result<Vec<DbItem>, Error> {
let mut stmt = self.conn.prepare("SELECT * FROM items;")?;
let items = stmt.query_map([], |row| {
Ok(DbItem {
id: row.get(0)?,
name: row.get(1)?,
description: row.get(2)?,
wikidata_id: row.get(3)?,
custom_properties: row.get(4)?,
})
})?;
let mut result = Vec::new();
for item in items {
result.push(item?);
}
Ok(result)
}
}
// Define a struct to represent an item in the database
#[derive(Debug, Deserialize, Serialize)]
pub struct DbItem {
pub id: String,
pub name: String,
pub description: String,
pub wikidata_id: Option<String>,
pub custom_properties: String,
}
}
// Define a struct to represent an item in the database
#[derive(Debug, Deserialize, Serialize)]
pub struct DbItem {
pub id: String,
pub name: String,
pub description: String,
pub wikidata_id: Option<String>,
pub custom_properties: String,
}
#[cfg(feature = "ssr")]
pub use db_impl::{Database, DbItem};

View file

@ -2,6 +2,7 @@ pub mod app;
pub mod components;
pub mod models;
pub mod nostr;
#[cfg(feature = "ssr")]
pub mod db;