Skip to content

Commit

Permalink
Merge pull request #29 from 0xBLCKLPTN/alice_database-dev
Browse files Browse the repository at this point in the history
PEST support for Instance Manager. Now Instance Manager can execute instructions from file.decl
  • Loading branch information
0xBLCKLPTN authored Oct 26, 2024
2 parents fdfb209 + c07302d commit 285e0ad
Show file tree
Hide file tree
Showing 10 changed files with 194 additions and 87 deletions.
6 changes: 4 additions & 2 deletions Plugins/Alice-Database/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
[package]
name = "Alice-Database_DBMS"
version = "1.2.0"
version = "1.2.2"
edition = "2021"
include = ["**/*.rs", "Cargo.toml","proto/*.proto"]
include = ["**/*.rs", "Cargo.toml","proto/*.proto", "src/syntax/*.pest", "src/test.decl"]
license = "MIT"
description = "The Alice-Database is a comprehensive data management solution designed to integrate seamlessly with the Kingdom System. This plugin provides robust functionality for creating, updating, and deleting collections and documents, ensuring efficient and reliable data storage and retrieva"
repository = "https://github.com/0xBLCKLPTN/Kingdom-System/tree/main/Plugins/Alice-Database"
Expand All @@ -13,6 +13,8 @@ homepage = "https://github.com/0xBLCKLPTN/Kingdom-System"
chrono = "0.4.38"
env_logger = "0.11.5"
log = "0.4.22"
pest = "2.7.14"
pest_derive = "2.7.14"
prost = "0.13.3"
rand = "0.8.5"
ring = "0.17.8"
Expand Down
27 changes: 27 additions & 0 deletions Plugins/Alice-Database/src/cli.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use std::io::{self, Write};
use crate::instance::*;

pub fn cli(instance_manager: &mut InstanceManager) {
loop {
print!("[ Instance Manager ] (type 'exit' to quit)=: ");
io::stdout().flush().unwrap();

let mut input = String::new();

match io::stdin().read_line(&mut input) {
Ok(_) => {
let trimmed_input = input.trim();

if trimmed_input.eq_ignore_ascii_case("exit") {
println!("Exiting...");
break;
}

instance_manager.wrapped_execute_cmd(trimmed_input);
}
Err(error) => {
println!("Error reading input: {}", error);
}
}
}
}
30 changes: 30 additions & 0 deletions Plugins/Alice-Database/src/command_executor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@

/* MIT License
Copyright (c) 2024 Daniil Ermolaev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. */

use pest_derive::Parser;
use pest::Parser;

#[derive(Parser)]
#[grammar = "syntax/instance_manager.pest"]
pub struct IMPestParser;

71 changes: 0 additions & 71 deletions Plugins/Alice-Database/src/grpc.rs

This file was deleted.

2 changes: 1 addition & 1 deletion Plugins/Alice-Database/src/grpc_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ impl InstanceService for GRPCInstanceManager

let engine_type = request.into_inner().engine_type;
let mut im = self.instance_manager.lock().unwrap();
let id = im.create_instance(&engine_type);
let id = im.create_instance(&engine_type).unwrap();

Ok(
Response::new( CreateInstanceResponse { instance: id } )
Expand Down
89 changes: 83 additions & 6 deletions Plugins/Alice-Database/src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,23 @@ SOFTWARE. */

use crate::Engines;
use uuid::Uuid;
use std::path::PathBuf;
use std::path::{PathBuf, Path};
use std::fs::File;
use std::io::{self, BufRead};
use crate::JSONEngine;
use std::collections::HashMap;
use ring::{rand::{SecureRandom, SystemRandom}, hmac};
use rand::rngs::OsRng;

use crate::IMPestParser;
use pest_derive::Parser;
use pest::Parser;
use crate::Rule;

macro_rules! adbprint {
($($arg:tt)*) => {
println!("[ INSTANCE MANAGER ]=: {}", format!($($arg)*));
};
}

#[derive(Debug, Clone)]
pub struct Instance {
Expand All @@ -53,16 +64,20 @@ impl InstanceManager {
Self {name, instances, root_path: root_path.to_owned(), authenticated_apps}
}

pub fn create_instance(&mut self, engine_type: &str) -> String {
pub fn create_instance(&mut self, engine_type: &str) -> Result<String, Box<dyn std::error::Error>> {
let instance_name: String = Uuid::new_v4().to_string();

let mut engine = match engine_type {
"json_engine" => Engines::JSONEngine(JSONEngine::new(&self.root_path)),
_ => panic!("Engine not found"),
_ => {
println!("Engine not found.");
return Err(Box::new(std::io::Error::new(
std::io::ErrorKind::InvalidInput, "Engine type not found")));
}
};
let mut instance = Instance {engine, name: instance_name.clone()};
self.instances.push(instance);
instance_name
Ok(instance_name)
}
pub fn get_instance(&self, instance_name: &str) -> Option<&Instance> {
self.instances.iter().find(|i| i.name == instance_name)
Expand All @@ -87,6 +102,68 @@ impl InstanceManager {
}

pub fn get_all_apps(&self) {
println!("{:#?}", self.authenticated_apps);
adbprint!("{:#?}", self.authenticated_apps);
}

pub fn execute_cmd(&mut self, command: &str) -> Result<(), Box<dyn std::error::Error>> {
match IMPestParser::parse(Rule::sql_statements, command) {
Ok(pairs) => {
for pair in pairs {
for inner_pair in pair.into_inner() {
match inner_pair.as_rule() {
Rule::create_instance => {
let inner = inner_pair.into_inner().as_str().split(" ENGINE ").collect::<Vec<_>>();
let instance_id = &self.create_instance(&inner[1]);
match instance_id {
Ok(message) => adbprint!("NEW INSTANCE ID: {}", message),
Err(e) => adbprint!("{:#?}",e)
}
},
Rule::get_instance => {
let inner = inner_pair.into_inner().as_str();
adbprint!("{:#?}", inner);
},
Rule::get_instances => {
adbprint!("{:#?}", self.instances);
},
Rule::print_addbms => {
adbprint!("{:#?}", self);
}
_ => unreachable!("I don't know this command"),
}
}
}
Ok(())
}
Err(e) => {
adbprint!("Error parsing command: {}", e);
Err(Box::new(e))
}
}
}

pub fn wrapped_execute_cmd(&mut self, command: &str) -> Result<(), Box<dyn std::error::Error>> {
match &self.execute_cmd(command) {
Ok(_) => println!(""),
Err(e) => adbprint!("Error! {}", e),
}
Ok(())
}

pub fn execute_decl_file<P>(&mut self, filename: P) -> Result<(), io::Error>
where
P: AsRef<Path> {
let file = File::open(filename)?;
let reader = io::BufReader::new(file);
let mut lines: Vec<String> = Vec::new();

for line in reader.lines() {
self.wrapped_execute_cmd(line?.replace("\n", "").as_str());
}
Ok(())
}
}




24 changes: 17 additions & 7 deletions Plugins/Alice-Database/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,21 +38,20 @@ pub mod engines;
pub mod grpc_server;
pub mod instance;
pub mod utils;
pub mod command_executor;
pub mod cli;

use json_engine::*;
use engines::*;
use grpc_server::*;
use instance::*;
use utils::*;

use command_executor::*;
use cli::cli;
/* gRPC
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
print_ascii();

let root_path = match prepare() {
Ok(k) => k,
_ => panic!("Errors in prepare function."),
};
let root_path: PathBuf = get_root_path();
let instance_manager = GRPCInstanceManager {
instance_manager: Arc::new(Mutex::new(InstanceManager::new(&root_path))),
Expand All @@ -67,3 +66,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
*/

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let root_path: PathBuf = get_root_path();

let mut im = InstanceManager::new(&root_path);
//let k = im.execute_decl_file(Path::new("./test.decl"));
cli(&mut im);
Ok(())
}
19 changes: 19 additions & 0 deletions Plugins/Alice-Database/src/syntax/instance_manager.pest
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
alpha = { 'a'..'z' | 'A'..'Z' }
digit = { '0'..'9' }
ident = { !digit ~ (alpha | digit | "_")+ }

item = { ident }
items = { item ~ (( "," | "," ) ~ item)* }

create_instance = { "CREATE INSTANCE " ~ ident ~ " ENGINE " ~ ident }
get_instance = { "GET INSTANCE " ~ ident }
get_instances = { "GET INSTANCES" }
delete_instance = { "DELETE INSTANCE " ~ ident }

print_addbms = { "PRINTALLDDBMS" }

sql_statement = {
create_instance | get_instance | get_instances | delete_instance | print_addbms
}

sql_statements = _{ sql_statement ~ ((";" ~ sql_statement) | (";" ~ sql_statement))* ~ ";"? }
3 changes: 3 additions & 0 deletions Plugins/Alice-Database/src/test.decl
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
CREATE INSTANCE new_instance ENGINE json_engine;
GET INSTANCES;
PRINTALLDDBMS;
10 changes: 10 additions & 0 deletions Plugins/Alice-Database/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,17 @@ const ADB_DATA_DIR: &str = "ADB_Data";
const JSON_ENGINE_DIR: &str = "json_engine";
const ADB_LOGS_DIR: &str = "ADB_Logs";

pub fn get_root_path() -> PathBuf {
let root_path = match prepare() {
Ok(k) => k,
_ => panic!("Errors while preparing..."),
};
return root_path;
}


pub fn prepare() -> std::io::Result<PathBuf> {
print_ascii();
// Get the home directory
let home_dir = env::home_dir().expect("Failed to get home directory");
let base_path = home_dir.join(ROOT_DIR);
Expand Down

0 comments on commit 285e0ad

Please sign in to comment.