Skip to content

Commit

Permalink
feat: Add explain analyze graphical feature for SQL performance vis…
Browse files Browse the repository at this point in the history
…ualization (#484)

* feat: Adding Query Profiling Support to BendSQL

* feat: edit the front-end page

* fix: handle case-insensitive check for "GRAPHICAL" in query

* fix: Correct time conversion in ProfileOverview component

* fix: query to lowercase

* fix: Remove frontend/** from excludes in licenserc.toml

* chore: Update copyright and license information in cli/src/web.rs

* fix: typo

* fix: lint

* fix: add a blank line after license

* fix: remove unsed dependency

* fix: remove the unused base64
  • Loading branch information
Maricaya authored Oct 23, 2024
1 parent 41061a6 commit a740b05
Show file tree
Hide file tree
Showing 43 changed files with 14,945 additions and 5 deletions.
5 changes: 5 additions & 0 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,23 @@ 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"
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();
if self.kind == QueryKind::ShowCreate {
print_expanded(schema, &rows)?;
Expand Down Expand Up @@ -279,6 +296,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::ShowCreate => (self.rows, "rows", "showcreate", 0, 0),
QueryKind::Query => (self.rows, "rows", "read", stats.read_rows, stats.read_bytes),
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
12 changes: 9 additions & 3 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,6 +625,7 @@ pub enum QueryKind {
Put,
Get,
AlterUserPassword,
Graphical,
ShowCreate,
}

Expand All @@ -633,12 +634,17 @@ impl From<&str> for QueryKind {
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::SHOW => match tz.next() {
Some(Ok(t)) if t.kind == TokenKind::CREATE => QueryKind::ShowCreate,
_ => QueryKind::Query,
},

TokenKind::PUT => QueryKind::Put,
TokenKind::GET => QueryKind::Get,
TokenKind::ALTER => {
Expand Down
81 changes: 81 additions & 0 deletions cli/src/web.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright 2021 Datafuse Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use actix_files as fs;
use actix_web::middleware::Logger;
use actix_web::{get, web, App, HttpResponse, HttpServer, Responder};
use anyhow::Result;
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;
}
}
4 changes: 2 additions & 2 deletions driver/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@
// 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

0 comments on commit a740b05

Please sign in to comment.