#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::{sync::Arc, time::Duration};
use egui::text::LayoutJob;
use egui::{Color32, FontId, TextFormat};
#[cfg(not(target_arch = "wasm32"))]
mod time_interface
{
pub(super) use std::time::Instant;
}
#[cfg(target_arch = "wasm32")]
mod time_interface
{
pub(super) use web_time::Instant;
}
use time_interface::Instant;
struct QueryExecutionContext
{
is_executing: bool,
start: Instant,
elapsed: Duration,
query_results: Option<gqlitedb::Result<gqlitedb::QueryResult>>,
}
fn highlight_cypher(ui: &egui::Ui, text: &str) -> LayoutJob
{
let mut job = LayoutJob::default();
let keywords = [
"MATCH", "CREATE", "MERGE", "RETURN", "WHERE", "WITH", "DELETE", "DETACH", "SET", "AND", "OR",
"NOT", "IN", "AS", "DISTINCT", "ORDER", "BY", "LIMIT", "SKIP",
];
for token in text.split_inclusive(|c: char| c.is_whitespace())
{
let word = token.trim();
let color = if keywords.contains(&word.to_uppercase().as_str())
{
if ui.visuals().dark_mode
{
Color32::LIGHT_BLUE
}
else
{
Color32::DARK_BLUE
}
}
else if word.starts_with('"') || word.starts_with('\'')
{
if ui.visuals().dark_mode
{
Color32::LIGHT_GREEN
}
else
{
Color32::DARK_GREEN
}
}
else if word.chars().all(|c| c.is_numeric())
{
ui.visuals().error_fg_color
}
else
{
ui.visuals().text_color()
};
job.append(
token,
0.0,
TextFormat {
font_id: FontId::monospace(14.0),
color,
..Default::default()
},
);
}
job
}
#[derive(serde::Deserialize, serde::Serialize)]
#[serde(default)] pub struct GqliteBrowser
{
history: Vec<String>,
query_text: String,
last_message: String,
postgres_url: String,
#[serde(skip)]
show_postgresql_dialog: bool,
#[serde(skip)]
result_delegate: ResultDelegate,
#[serde(skip)]
connection_error: String,
#[serde(skip)]
no_results: bool,
#[serde(skip)]
connection: Option<std::sync::Arc<gqlitedb::Connection>>,
#[serde(skip)]
status_message: String,
#[serde(skip)]
query_execution_context: ccutils::sync::ArcMutex<QueryExecutionContext>,
}
impl Default for GqliteBrowser
{
fn default() -> Self
{
Self {
history: Default::default(),
query_text: Default::default(),
last_message: Default::default(),
postgres_url: "postgres://postgres:postgres@localhost:5432".to_string(),
show_postgresql_dialog: false,
result_delegate: ResultDelegate {
results: Default::default(),
},
no_results: false,
connection_error: String::new(),
connection: None,
status_message: "Welcome to GQLite Browser!".to_string(),
query_execution_context: QueryExecutionContext {
is_executing: false,
start: Instant::now(),
elapsed: Default::default(),
query_results: None,
}
.into(),
}
}
}
impl GqliteBrowser
{
pub fn new(cc: &eframe::CreationContext<'_>) -> Self
{
if let Some(storage) = cc.storage
{
eframe::get_value(storage, eframe::APP_KEY).unwrap_or_default()
}
else
{
Default::default()
}
}
fn execute_oc_query(&mut self, ctx: &egui::Context)
{
if let Some(connection) = &self.connection
{
let query_execution_context = self.query_execution_context.clone();
{
let mut query_execution_context = query_execution_context.lock().unwrap();
if query_execution_context.is_executing
{
return;
}
query_execution_context.is_executing = true;
query_execution_context.start = Instant::now();
}
self.history.retain(|v| *v != self.query_text);
self.history.push(self.query_text.to_owned());
let connection = connection.to_owned();
let query_text = self.query_text.to_owned();
let ctx = ctx.clone();
let f = move || {
let start = Instant::now();
let result = connection.execute_oc_query(&query_text, Default::default());
let elapsed = start.elapsed();
let mut query_execution_context = query_execution_context.lock().unwrap();
query_execution_context.is_executing = false;
query_execution_context.elapsed = elapsed;
query_execution_context.query_results = Some(result);
ctx.request_repaint();
};
#[cfg(target_arch = "wasm32")]
{
f()
}
#[cfg(not(target_arch = "wasm32"))]
{
std::thread::spawn(f);
}
}
}
fn set_connection(&mut self, connection: gqlitedb::Result<gqlitedb::Connection>)
{
match connection
{
Ok(connection) => self.connection = Some(Arc::new(connection)),
Err(e) =>
{
self.connection = None;
self.connection_error = format!("{:?}", e);
}
}
}
fn create_connection(&mut self, backend: impl Into<String>)
{
self.set_connection(gqlitedb::Connection::create(
gqlitedb::value_map! {"backend" => backend.into()},
));
}
fn create_postgres_connection(&mut self)
{
self.set_connection(gqlitedb::Connection::create(
gqlitedb::value_map! {"backend" => "postgres", "url" => self.postgres_url.clone()},
));
}
#[cfg(not(target_arch = "wasm32"))]
fn new_database(&mut self, backend: impl Into<String>)
{
let filename = rfd::FileDialog::new().save_file().unwrap();
if std::fs::exists(&filename).unwrap()
{
self.connection = None;
self.connection_error = format!("'{:?}' already exists, did you want to open?", filename);
}
else
{
let connection = gqlitedb::Connection::builder()
.options(gqlitedb::value_map! {"backend" => backend.into()})
.path(filename)
.create();
self.set_connection(connection);
}
}
#[cfg(not(target_arch = "wasm32"))]
fn open_database(&mut self)
{
let filename = rfd::FileDialog::new().pick_file().unwrap();
if std::fs::exists(&filename).unwrap()
{
let connection = gqlitedb::Connection::builder().path(filename).create();
self.set_connection(connection);
}
else
{
self.connection = None;
self.connection_error = format!("'{:?}' does not exists.", filename);
}
}
#[cfg(not(target_arch = "wasm32"))]
fn support_opening() -> bool
{
true
}
#[cfg(not(target_arch = "wasm32"))]
fn support_quitting() -> bool
{
true
}
#[cfg(target_arch = "wasm32")]
fn new_database(&mut self, _backend: impl Into<String>) {}
#[cfg(target_arch = "wasm32")]
fn open_database(&mut self) {}
#[cfg(target_arch = "wasm32")]
fn support_opening() -> bool
{
false
}
#[cfg(target_arch = "wasm32")]
fn support_quitting() -> bool
{
false
}
}
brisk_eframe::brisk_it! {
Main
{
title: "GQLite Browser",
viewport: Viewport
{
inner_size: [320.0, 240.0],
},
App {
target: GqliteBrowser,
save: true,
Eval {
expression: {
let mut query_execution_context = self.query_execution_context.lock().unwrap();
if let Some(query_results) = query_execution_context.query_results.take()
{
self.no_results = false;
self.last_message.clear();
match query_results
{
Ok(t) => match t
{
gqlitedb::QueryResult::Table(table) =>
{
self.status_message = format!(
"Query executed in {:.3} s, resulting in {} rows.",
query_execution_context.elapsed.as_secs_f64(),
table.rows()
);
self.result_delegate.results = table;
}
_ =>
{
self.no_results = true;
self.status_message = format!(
"Query executed in {:.3} s.",
query_execution_context.elapsed.as_secs_f64()
);
self.result_delegate.results = Default::default();
}
},
Err(err) =>
{
self.last_message = match err.error()
{
gqlitedb::Error::CompileTime(ct) =>
{
format!("Compilation error:\n{}", ct)
}
_ =>
{
format!("Query execution failed: {:?}", err)
}
}
}
}
} else if query_execution_context.is_executing
{
self.status_message = format!(
"Query executing for {:.1} s...",
(Instant::now() - query_execution_context.start).as_secs_f64()
);
ctx.request_repaint_after(Duration::from_millis(100));
}
}
},
Window {
title: "Configure postgres connection",
visible: self.show_postgresql_dialog,
Label
{
id: posgres_url_label,
text: "Url"
},
TextEdit
{
labelled_by: posgres_url_label.id,
text: &mut self.postgres_url,
on_editing_finished: {
}
},
Horizontal
{
Button {
text: "Connect",
on_clicked: {
self.show_postgresql_dialog = false;
self.create_postgres_connection();
},
},
Button {
text: "Cancel",
on_clicked: self.show_postgresql_dialog = false,
}
}
},
TopBottomPanel {
id: top,
position: Top,
MenuBar {
MenuButton {
text: "Connection",
Button {
text: "New sqlite (in-memory)",
visible: gqlitedb::Connection::available_backends().contains(&"sqlite".to_string()),
on_clicked: self.create_connection("sqlite")
},
Button {
text: "New redb (in-memory)",
visible: gqlitedb::Connection::available_backends().contains(&"redb".to_string()),
on_clicked: self.create_connection("redb")
},
Button {
text: "New sqlite (file)",
visible: gqlitedb::Connection::available_backends().contains(&"sqlite".to_string()) && Self::support_opening(),
on_clicked: self.new_database("sqlite")
},
Button {
text: "New redb (file)",
visible: gqlitedb::Connection::available_backends().contains(&"redb".to_string()) && Self::support_opening(),
on_clicked: self.new_database("redb")
},
Button {
text: "Open (file)",
visible: gqlitedb::Connection::available_backends().contains(&"sqlite".to_string()) && Self::support_opening(),
on_clicked: self.open_database()
},
Button {
text: "Connect to postgres",
visible: gqlitedb::Connection::available_backends().contains(&"postgres".to_string()),
on_clicked: self.show_postgresql_dialog = true
},
Button {
text: "Quit",
visible: Self::support_quitting(),
on_clicked: {
ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
}
}
}
},
},
CentralPanel
{
visible: self.connection.is_none(),
Label
{
visible: self.connection_error.is_empty(),
text: "No connection...",
},
Label
{
visible: !self.connection_error.is_empty(),
text: format!("\u{f8b6} {}", self.connection_error)
}
},
CentralPanel
{
visible: self.connection.is_some(),
Eval
{
expression: {
if self.query_execution_context.lock().unwrap().is_executing
{
ui.disable();
}
}
},
Horizontal
{
Label
{
id: name_label,
text: "Prompt: "
},
TextEdit
{
text: &mut self.query_text,
labelled_by: name_label.id,
hint_text: "Write an OpenCypher query, and then press enter to execute.",
on_editing_finished: { self.execute_oc_query(&ctx); },
layouter: &mut |ui, text, wrap_width| {
let mut job = highlight_cypher(ui, text.as_str());
job.wrap.max_width = wrap_width;
ui.fonts_mut(|f| f.layout_job(job))
}
},
Button
{
text: "history ⬇",
PopupMenu {
Repeater
{
target: query,
model: self.history.iter().rev(),
Button {
text: query,
on_clicked: self.query_text = query.to_owned()
}
}
}
}
},
Label
{
visible: self.no_results,
text: "No results.",
},
Label
{
visible: !self.last_message.is_empty(),
text: format!("\u{f8b6} {}", self.last_message)
},
Table {
visible: !self.result_delegate.results.is_empty(),
table_delegate: &mut self.result_delegate,
num_rows: self.result_delegate.num_rows() as u64,
columns: vec![egui_table::Column::new(100.0)
.range(10.0..=500.0)
.resizable(true); self.result_delegate.num_columns()],
auto_size_mode: egui_table::AutoSizeMode::OnParentResize,
headers: [
HeaderRow {
height: 24.0,
}
]
},
},
TopBottomPanel {
id: bottom,
position: Bottom,
Label
{
text: &self.status_message,
}
},
}
}
}
struct ResultDelegate
{
results: gqlitedb::Table,
}
impl ResultDelegate
{
fn num_rows(&self) -> usize
{
self.results.rows()
}
fn num_columns(&self) -> usize
{
self.results.columns()
}
fn cell_content_ui(&mut self, row_nr: usize, col_nr: usize, ui: &mut egui::Ui)
{
brisk_egui::brisk_it! {
Label
{
text: format!("{}", self.results.value(row_nr, col_nr).unwrap()),
}
}
}
}
impl egui_table::TableDelegate for ResultDelegate
{
fn header_cell_ui(&mut self, ui: &mut egui::Ui, cell_inf: &egui_table::HeaderCellInfo)
{
let egui_table::HeaderCellInfo { group_index, .. } = cell_inf;
let margin = 4;
let row: &Vec<String> = self.results.headers();
egui::Frame::NONE
.inner_margin(egui::Margin::symmetric(margin, 0))
.show(ui, |ui| {
ui.heading(row[*group_index].to_string());
});
}
fn cell_ui(&mut self, ui: &mut egui::Ui, cell_info: &egui_table::CellInfo)
{
let egui_table::CellInfo { row_nr, col_nr, .. } = *cell_info;
if row_nr % 2 == 1
{
ui.painter()
.rect_filled(ui.max_rect(), 0.0, ui.visuals().faint_bg_color);
}
egui::Frame::NONE
.inner_margin(egui::Margin::symmetric(4, 0))
.show(ui, |ui| {
self.cell_content_ui(row_nr as usize, col_nr, ui);
});
}
}