Skip to content

Commit

Permalink
refactor controller
Browse files Browse the repository at this point in the history
  • Loading branch information
RGGH committed Mar 21, 2024
1 parent 6a48f74 commit 99f6b58
Show file tree
Hide file tree
Showing 18 changed files with 119 additions and 104 deletions.
Binary file removed db/000146.sst
Binary file not shown.
Binary file removed db/000149.sst
Binary file not shown.
Binary file removed db/000154.sst
Binary file not shown.
Binary file added db/000169.sst
Binary file not shown.
Binary file added db/000172.sst
Binary file not shown.
Binary file added db/000177.sst
Binary file not shown.
2 changes: 1 addition & 1 deletion db/CURRENT
Original file line number Diff line number Diff line change
@@ -1 +1 @@
MANIFEST-000156
MANIFEST-000179
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Binary file removed db/MANIFEST-000156
Binary file not shown.
Binary file added db/MANIFEST-000179
Binary file not shown.
File renamed without changes.
File renamed without changes.
1 change: 1 addition & 0 deletions src/controller.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod utils;
91 changes: 91 additions & 0 deletions src/controller/utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
use surrealdb::{engine::local::Db, Surreal};
use crate::Colorize;
use crate::{Magazine, Record};

pub async fn add_to(db: &Surreal<Db>, data: Vec<Magazine>) -> surrealdb::Result<()> {
for magazine in data {
let response = db
.query(
"CREATE product SET name=$name,
price=$price, day=$day, month=$month, year=$year",
)
.bind(("name", magazine.name))
.bind(("price", magazine.price))
.bind(("day", magazine.day))
.bind(("month", magazine.month))
.bind(("year", magazine.year))
.await?;

match response.check() {
Ok(_) => {}
Err(err) => {
eprintln!("Could not add entry: '{}'", err);
return Err(err);
}
};
}
Ok(())
}

pub async fn list_all(db: &Surreal<Db>) -> surrealdb::Result<()> {
let mut entries = db
.query(
"SELECT name, price, day, month, year, id
FROM type::table($table) ORDER BY name ASC",
)
.bind(("table", "product"))
.await?;
let entries: Vec<Record> = entries.take(0)?;
println!("----------------------------------------------------------------");
println!(
"{:<12} {:5} {:<2} {:<2} {:<2} {:}",
"Magazine", "price", "day", "month", "year", "table+id"
);
println!("----------------------------------------------------------------");
for entry in entries {
println!(
"{:<12} {:<5.2} {:<3} {:<5} {:<4} {:}",
entry.name.yellow(),
entry.price,
entry.day,
entry.month,
entry.year,
entry.id.to_raw().blue()
);
}

Ok(())
}

pub async fn list_year(db: &Surreal<Db>, year: u32) -> surrealdb::Result<()> {
let mut entries = db
.query("SELECT * FROM type::table($table) WHERE year=$year")
.bind(("table", "product"))
.bind(("year", year))
.await?;
let entries: Vec<Magazine> = entries.take(0)?;
for entry in entries {
println!("{:?} ", entry);
}
Ok(())
}

pub async fn add_relate(db: &Surreal<Db>, topic: String) -> surrealdb::Result<()> {
let _relate = db
.query("RELATE product->featured->($topic)")
.bind(("topic", topic))
.await?;
Ok(())
}

pub async fn list_related(db: &Surreal<Db>) -> surrealdb::Result<()> {
let mut entries = db
.query("SELECT * FROM type::table($table)")
.bind(("table", "featured"))
.await?;
let entries: Vec<Record> = entries.take(0)?;
for entry in entries {
println!("{:?} ", entry);
}
Ok(())
}
129 changes: 26 additions & 103 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
// run as ./target/debug/surrealtest 13 2 1998
// run as ./target/debug/surrealtest add 13 2 1998
#![allow(unused)]
use std::fmt::format;

use clap::Parser;
use colored::Colorize;
use controller::utils::*;
use serde::Deserialize;
use std::fmt::format;
use surrealdb::engine::local::Db;
use surrealdb::engine::local::RocksDb;
use surrealdb::sql::Thing;
use surrealdb::Surreal;
//use surrealkv::Store;

mod controller;

#[derive(Parser, Debug)]
struct Value {
pub struct Value {
/// add product
add: String,
/// day number to add
number_day: i32,
/// month number to add
Expand All @@ -22,7 +26,7 @@ struct Value {
}

#[derive(Debug, Deserialize)]
struct Magazine {
pub struct Magazine {
name: String,
price: f32,
day: u8,
Expand All @@ -31,7 +35,7 @@ struct Magazine {
}

#[derive(Debug, Deserialize)]
struct Record {
pub struct Record {
id: Thing,
name: String,
price: f32,
Expand All @@ -42,20 +46,24 @@ struct Record {

#[tokio::main]
async fn main() -> surrealdb::Result<()> {
// handle user input
let value = Value::parse();

let day = value.number_day;
let month = value.number_month;
let year = value.number_year;

let next = format!("Day:{} Month:{} Year:{}",day,month,year);

let day: u8 = value.number_day.try_into().unwrap();
let month: u8 = value.number_month.try_into().unwrap();
let year: u32 = value.number_year.try_into().unwrap();
let next = format!("Day:{} Month:{} Year:{}", day, month, year);
println!("{}", next.green());
let new_mag = Magazine {
name: "Autosport".to_string(),
price: 2.30,
day,
month,
year,
};

// Create database connection
let mut db_path = std::env::current_dir().unwrap();
db_path.push("db");
//println!("{db_path:?}");

// use embedded RocksDB for storage -try SurrealKV as soon as it compiles ok
let db = Surreal::new::<RocksDb>(db_path).await?;
Expand All @@ -64,15 +72,15 @@ async fn main() -> surrealdb::Result<()> {
// Select specific namespace & database
db.use_ns("test").use_db("test").await?;

// clear old, test data
let _cleanup = db.query("REMOVE TABLE product").await?;

let _response = db
//-- Create an index on the name, month and year fields of the product table
// DEFINE INDEX test ON user FIELDS account, email;
.query("DEFINE INDEX magid ON TABLE product COLUMNS name,month,year UNIQUE")
.await?;

let data = vec![
let mut data = vec![
Magazine {
name: "Autosport".to_string(),
price: 1.80,
Expand Down Expand Up @@ -102,7 +110,9 @@ async fn main() -> surrealdb::Result<()> {
year: 1984,
},
];
data.push(new_mag);

// Banner - read from seperate file for customizing
println!(
r"
__ ____
Expand All @@ -125,90 +135,3 @@ async fn main() -> surrealdb::Result<()> {
Ok(())
}

async fn add_to(db: &Surreal<Db>, data: Vec<Magazine>) -> surrealdb::Result<()> {
for magazine in data {
let response = db
.query(
"CREATE product SET name=$name,
price=$price, day=$day, month=$month, year=$year",
)
.bind(("name", magazine.name))
.bind(("price", magazine.price))
.bind(("day", magazine.day))
.bind(("month", magazine.month))
.bind(("year", magazine.year))
.await?;

match response.check() {
Ok(_) => {}
Err(err) => {
eprintln!("Could not add entry: '{}'", err);
return Err(err);
}
};
}
Ok(())
}

async fn list_all(db: &Surreal<Db>) -> surrealdb::Result<()> {
let mut entries = db
.query(
"SELECT name, price, day, month, year, id
FROM type::table($table) ORDER BY name ASC",
)
.bind(("table", "product"))
.await?;
let entries: Vec<Record> = entries.take(0)?;
println!("----------------------------------------------------------------");
println!(
"{:<12} {:5} {:<2} {:<2} {:<2} {:}",
"Magazine", "price", "day", "month", "year", "table+id"
);
println!("----------------------------------------------------------------");
for entry in entries {
println!(
"{:<12} {:<5.2} {:<3} {:<5} {:<4} {:}",
entry.name.yellow(),
entry.price,
entry.day,
entry.month,
entry.year,
entry.id.to_raw().blue()
);
}

Ok(())
}

async fn list_year(db: &Surreal<Db>, year: u32) -> surrealdb::Result<()> {
let mut entries = db
.query("SELECT * FROM type::table($table) WHERE year=$year")
.bind(("table", "product"))
.bind(("year", year))
.await?;
let entries: Vec<Magazine> = entries.take(0)?;
for entry in entries {
println!("{:?} ", entry);
}
Ok(())
}

async fn add_relate(db: &Surreal<Db>, topic: String) -> surrealdb::Result<()> {
let _relate = db
.query("RELATE product->featured->($topic)")
.bind(("topic", topic))
.await?;
Ok(())
}

async fn list_related(db: &Surreal<Db>) -> surrealdb::Result<()> {
let mut entries = db
.query("SELECT * FROM type::table($table)")
.bind(("table", "featured"))
.await?;
let entries: Vec<Record> = entries.take(0)?;
for entry in entries {
println!("{:?} ", entry);
}
Ok(())
}

0 comments on commit 99f6b58

Please sign in to comment.