Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add explain analyze graphical feature for SQL performance visualization #484

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,24 @@ percent-encoding = "2.3"
sled = "0.34"
rustyline = "12.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
terminal_size = "0.3"
tokio = { version = "1.34", features = [
"macros",
"rt",
"rt-multi-thread",
"sync",
"parking_lot",
"full"
] }
toml = "0.8"
tracing-appender = "0.2"
unicode-segmentation = "1.10"
url = { version = "2.5", default-features = false }
actix-web = "4.0"
actix-rt = "2.6"
webbrowser = "1.0.1"
actix-files = "0.6"

[build-dependencies]
vergen = { version = "8.2", features = ["build", "git", "gix"] }
Expand Down
18 changes: 18 additions & 0 deletions cli/src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ use crate::{
ast::{format_query, highlight_query},
config::{ExpandMode, OutputFormat, OutputQuoteStyle, Settings},
session::QueryKind,
web::start_server_and_open_browser,
};

#[async_trait::async_trait]
Expand Down Expand Up @@ -140,6 +141,22 @@ impl<'a> FormatDisplay<'a> {
return Ok(());
}

if self.kind == QueryKind::Graphical {
println!("Graphical query result: -- ");
let mut explain_results = Vec::new();
for result in &rows {
explain_results.push(result.values()[0].to_string());
}

tokio::spawn(async move {
if let Err(e) = start_server_and_open_browser(explain_results.join("")).await {
eprintln!("Failed to start server: {}", e);
}
});

return Ok(());
}

let schema = self.data.schema();
match self.settings.expand {
ExpandMode::On => {
Expand Down Expand Up @@ -274,6 +291,7 @@ impl<'a> FormatDisplay<'a> {
stats.normalize();

let (rows, mut rows_str, kind, total_rows, total_bytes) = match self.kind {
QueryKind::Graphical => (self.rows, "rows", "graphical", 0, 0),
QueryKind::Explain => (self.rows, "rows", "explain", 0, 0),
QueryKind::Query => (self.rows, "rows", "read", stats.read_rows, stats.read_bytes),
QueryKind::Update | QueryKind::AlterUserPassword => (
Expand Down
1 change: 1 addition & 0 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ mod display;
mod helper;
mod session;
mod trace;
mod web;

use std::{
collections::BTreeMap,
Expand Down
11 changes: 9 additions & 2 deletions cli/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ const ALTER_USER_PASSWORD_TOKENS: [TokenKind; 6] = [

pub struct Session {
client: Client,
conn: Box<dyn Connection>,
pub conn: Box<dyn Connection>,
is_repl: bool,

settings: Settings,
Expand Down Expand Up @@ -625,14 +625,21 @@ pub enum QueryKind {
Put,
Get,
AlterUserPassword,
Graphical,
}

impl From<&str> for QueryKind {
fn from(query: &str) -> Self {
let mut tz = Tokenizer::new(query);
match tz.next() {
Some(Ok(t)) => match t.kind {
TokenKind::EXPLAIN => QueryKind::Explain,
TokenKind::EXPLAIN => {
if query.to_lowercase().contains("graphical") {
QueryKind::Graphical
} else {
QueryKind::Explain
}
},
TokenKind::PUT => QueryKind::Put,
TokenKind::GET => QueryKind::Get,
TokenKind::ALTER => {
Expand Down
73 changes: 73 additions & 0 deletions cli/src/web.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
use anyhow::Result;

use actix_web::{App, get, HttpResponse, HttpServer, Responder, web};
use actix_web::middleware::Logger;
use actix_files as fs;
use tokio::net::TcpListener;


struct AppState {
result: String,
}

#[get("/api/message")]
async fn get_message(data: web::Data<AppState>) -> impl Responder {
let response = serde_json::json!({
"result": data.result,
});
HttpResponse::Ok().json(response)
}

pub async fn start_server_and_open_browser<'a>(explain_result: String) -> Result<()> {
let port = find_available_port(8080).await;
let server = tokio::spawn(async move {
start_server(port, explain_result.to_string()).await;
});

// Open the browser in a separate task
tokio::spawn(async move {
if webbrowser::open(&format!("http://127.0.0.1:{}", port)).is_ok() {
// eprintln!("Browser opened successfully at http://127.0.0.1:{}", port);
} else {
println!("Failed to open browser.");
}
});

// Continue with the rest of the code
server.await.expect("Server task failed");

Ok(())
}

pub async fn start_server<'a>(port: u16, result: String) {
let app_state = web::Data::new(AppState {
result: result.clone(),
});

HttpServer::new(move || {
App::new()
.wrap(Logger::default())
.app_data(app_state.clone())
.service(get_message)
.service(
fs::Files::new("/", "./frontend/build").index_file("index.html")
)
})
.bind(("127.0.0.1", port))
.expect("Cannot bind to port")
.run()
.await
.expect("Server run failed");
}



async fn find_available_port(start: u16) -> u16 {
let mut port = start;
loop {
if TcpListener::bind(("127.0.0.1", port)).await.is_ok() {
return port;
}
port += 1;
}
}
1 change: 1 addition & 0 deletions core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ tokio-retry = "0.3"
tokio-util = { version = "0.7", features = ["io-util"] }
url = { version = "2.5", default-features = false }
uuid = { version = "1.6", features = ["v4"] }
base64 = "0.22.1"

[dev-dependencies]
chrono = { workspace = true }
5 changes: 3 additions & 2 deletions driver/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.

mod conn;

pub mod conn;
#[cfg(feature = "flight-sql")]
mod flight_sql;
mod rest_api;
pub mod rest_api;

pub use conn::{Client, Connection, ConnectionInfo};

Expand Down
23 changes: 23 additions & 0 deletions frontend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
46 changes: 46 additions & 0 deletions frontend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Getting Started with Create React App

This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).

## Available Scripts

In the project directory, you can run:

### `npm start`

Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.

The page will reload if you make edits.\
You will also see any lint errors in the console.

### `npm test`

Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.

### `npm run build`

Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

### `npm run eject`

**Note: this is a one-way operation. Once you `eject`, you can’t go back!**

If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

## Learn More

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).

To learn React, check out the [React documentation](https://reactjs.org/).
53 changes: 53 additions & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"@ant-design/charts": "v1",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.101",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"antd": "^5.19.1",
"lodash-es": "^4.17.21",
"pretty-ms": "^9.1.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"typescript": "^4.9.5",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@types/lodash-es": "^4.17.12",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.47",
"tailwindcss": "^3.4.13"
}
}
6 changes: 6 additions & 0 deletions frontend/postcss.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
14 changes: 14 additions & 0 deletions frontend/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/logo.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<title>Databend</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
16 changes: 16 additions & 0 deletions frontend/public/logo.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading