Compare commits
3 Commits
6df8e53b53
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| b692a58ee2 | |||
| 78aaf83d6e | |||
| 43ce34219c |
62
GEMINI.md
Normal file
62
GEMINI.md
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
# Gemini Project Analysis: dbPrompt
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
The `dbPrompt` project is a web-based application that provides a user interface for executing SQL queries against a MySQL database. It keeps a history of all executed queries and their results, which are displayed on the main page.
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
- `dbPrompt.go`: The main application file, written in Go. It contains the web server and all the backend logic.
|
||||||
|
- `index.html`: A single HTML file that contains the entire frontend UI, including CSS and JavaScript.
|
||||||
|
- `go.mod` / `go.sum`: Go module files that define the project's dependencies. The only external dependency is the MySQL driver for Go.
|
||||||
|
- `config.json`: A configuration file for the database connection details (hostname, username, password, etc.).
|
||||||
|
- `history/`: A directory where the history of executed queries is stored as JSON files.
|
||||||
|
- `README.md`: The project's README file.
|
||||||
|
- `LICENSE`: The project's license file.
|
||||||
|
|
||||||
|
## Backend (Go)
|
||||||
|
|
||||||
|
The backend is a simple web server built with the standard `net/http` package in Go.
|
||||||
|
|
||||||
|
- **Database Connection**: It connects to a MySQL database using the `go-sql-driver/mysql` driver. Connection parameters are read from `config.json`.
|
||||||
|
- **Endpoints**:
|
||||||
|
- `GET /`: Serves the `index.html` file.
|
||||||
|
- `POST /query`: Receives a SQL query from the frontend, executes it on the database, and returns the result as JSON. It handles both queries that return rows (e.g., `SELECT`) and statements that modify data (e.g., `INSERT`, `UPDATE`). Each executed query and its result are saved to a JSON file in the `history/` directory.
|
||||||
|
- `DELETE /history/{id}`: Deletes a specific query history item (JSON file) based on its ID from the `history/` directory.
|
||||||
|
- `GET /history/`: Reads all query history files from the `history/` directory, sorts them chronologically, and returns them as a single JSON array.
|
||||||
|
- **Query Execution Metadata**: The backend now captures and includes the `duration` (in milliseconds) of each query execution in the `QueryResult` object before saving it to history and sending it to the frontend.
|
||||||
|
|
||||||
|
## Frontend (HTML, CSS, JavaScript)
|
||||||
|
|
||||||
|
The frontend is a single-page application contained entirely within `index.html`.
|
||||||
|
|
||||||
|
- **User Interface**: The UI is composed of "query blocks". Each block contains a textarea for writing a SQL query, a "Run Query" button, and a result area.
|
||||||
|
- **History**: On page load, the application fetches the query history from the `/history/` endpoint and populates the page with query blocks for each historical query. One empty query block is always present for entering new queries.
|
||||||
|
- **Interaction**:
|
||||||
|
- Users can type a SQL query into a textarea and click "Run Query".
|
||||||
|
- The JavaScript code sends the query to the `/query` endpoint.
|
||||||
|
- The result (a table of data, a message with rows affected, or an error) is displayed in the result area of the corresponding query block.
|
||||||
|
- Successfully running a query in the "new query" block will automatically add a new empty block below it and equip the executed block with a "Delete" button.
|
||||||
|
- **Delete Functionality**:
|
||||||
|
- Historical query blocks now include a "Delete" button.
|
||||||
|
- When clicked, a confirmation dialog appears. If confirmed, a `DELETE` request is sent to the backend (`/history/{id}`), and the block is removed from the UI.
|
||||||
|
- The designated "new query" block (for new input) does not initially have a delete button.
|
||||||
|
- **Query Result Collapsibility**:
|
||||||
|
- Tabular query results are now wrapped in a collapsible section, allowing users to expand and collapse them.
|
||||||
|
- "Collapse All" and "Expand All" buttons have been added to the header, enabling users to manage the visibility of all result tables simultaneously.
|
||||||
|
- By default, all result tables are expanded.
|
||||||
|
- **Query Execution Metadata Display**: Each query result now displays the exact date and time of execution and its processing duration (in milliseconds).
|
||||||
|
|
||||||
|
## How it Works
|
||||||
|
|
||||||
|
1. The user opens the web page, and the browser loads `index.html`.
|
||||||
|
2. The JavaScript in `index.html` makes a `GET` request to `/history/` to load past queries.
|
||||||
|
3. The Go backend reads the JSON files from the `history/` directory and returns them.
|
||||||
|
4. The frontend dynamically creates a "query block" for each past query (with a delete button) and one new empty block (without a delete button).
|
||||||
|
5. The user enters a new SQL query into the designated "new query" block and clicks "Run Query".
|
||||||
|
6. The frontend sends a `POST` request to `/query` with the query string.
|
||||||
|
7. The Go backend executes the query against the MySQL database, measures its duration, and saves the query, result, timestamp, and duration to a new JSON file in the `history/` directory.
|
||||||
|
8. The backend returns the result (including duration) to the frontend.
|
||||||
|
9. The frontend displays the result in the corresponding query block, along with the execution date/time and duration. If it was a "new query" block, it gets a delete button, and a new empty "new query" block is added below it.
|
||||||
|
10. Users can click the "Delete" button on historical queries to remove them.
|
||||||
|
11. Users can collapse/expand individual result tables or use the global "Collapse All" / "Expand All" buttons.
|
||||||
40
build.bat
Normal file
40
build.bat
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
@echo off
|
||||||
|
setlocal
|
||||||
|
|
||||||
|
echo ==============================
|
||||||
|
echo Building Go binaries...
|
||||||
|
echo ==============================
|
||||||
|
|
||||||
|
set APP_NAME=dbPrompt
|
||||||
|
|
||||||
|
REM Create output folder
|
||||||
|
if not exist dist mkdir dist
|
||||||
|
|
||||||
|
REM Windows build
|
||||||
|
echo Building Windows...
|
||||||
|
set GOOS=windows
|
||||||
|
set GOARCH=amd64
|
||||||
|
go build -o dist\%APP_NAME%-windows-amd64.exe
|
||||||
|
|
||||||
|
if errorlevel 1 goto error
|
||||||
|
|
||||||
|
REM Linux build
|
||||||
|
echo Building Linux...
|
||||||
|
set GOOS=linux
|
||||||
|
set GOARCH=amd64
|
||||||
|
go build -o dist\%APP_NAME%-linux-amd64
|
||||||
|
|
||||||
|
if errorlevel 1 goto error
|
||||||
|
|
||||||
|
echo ==============================
|
||||||
|
echo Build completed successfully!
|
||||||
|
echo Output in dist\
|
||||||
|
goto end
|
||||||
|
|
||||||
|
:error
|
||||||
|
echo.
|
||||||
|
echo BUILD FAILED!
|
||||||
|
exit /b 1
|
||||||
|
|
||||||
|
:end
|
||||||
|
endlocal
|
||||||
154
dbPrompt.go
154
dbPrompt.go
@ -2,6 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"embed"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
@ -17,6 +18,9 @@ import (
|
|||||||
_ "github.com/go-sql-driver/mysql"
|
_ "github.com/go-sql-driver/mysql"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
//go:embed index.html static/*
|
||||||
|
var embeddedFiles embed.FS
|
||||||
|
|
||||||
// Config struct for database connection
|
// Config struct for database connection
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
@ -34,13 +38,14 @@ type QueryRequest struct {
|
|||||||
|
|
||||||
// QueryResult represents a single historical query execution
|
// QueryResult represents a single historical query execution
|
||||||
type QueryResult struct {
|
type QueryResult struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Query string `json:"query"`
|
Query string `json:"query"`
|
||||||
Timestamp int64 `json:"timestamp"`
|
Timestamp int64 `json:"timestamp"`
|
||||||
Error string `json:"error,omitempty"`
|
Duration int64 `json:"duration,omitempty"` // Duration in milliseconds
|
||||||
Columns []string `json:"columns,omitempty"`
|
Error string `json:"error,omitempty"`
|
||||||
Rows [][]interface{} `json:"rows,omitempty"`
|
Columns []string `json:"columns,omitempty"`
|
||||||
RowsAffected int64 `json:"rowsAffected,omitempty"`
|
Rows [][]interface{} `json:"rows,omitempty"`
|
||||||
|
RowsAffected int64 `json:"rowsAffected,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
var db *sql.DB
|
var db *sql.DB
|
||||||
@ -80,10 +85,13 @@ func main() {
|
|||||||
os.Mkdir(historyDir, 0755)
|
os.Mkdir(historyDir, 0755)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Serve static files
|
||||||
|
fs := http.FS(embeddedFiles)
|
||||||
|
|
||||||
// HTTP Handlers
|
// HTTP Handlers
|
||||||
http.HandleFunc("/", serveIndex)
|
http.Handle("/", http.FileServer(fs))
|
||||||
http.HandleFunc("/query", handleQuery)
|
http.HandleFunc("/query", handleQuery)
|
||||||
http.HandleFunc("/history", handleHistory)
|
http.HandleFunc("/history/", handleHistory)
|
||||||
|
|
||||||
log.Println("Starting server on :8080...")
|
log.Println("Starting server on :8080...")
|
||||||
if err := http.ListenAndServe(":8080", nil); err != nil {
|
if err := http.ListenAndServe(":8080", nil); err != nil {
|
||||||
@ -96,33 +104,68 @@ func serveIndex(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func handleHistory(w http.ResponseWriter, r *http.Request) {
|
func handleHistory(w http.ResponseWriter, r *http.Request) {
|
||||||
files, err := ioutil.ReadDir(historyDir)
|
switch r.Method {
|
||||||
if err != nil {
|
case http.MethodGet:
|
||||||
http.Error(w, "Could not read history", http.StatusInternalServerError)
|
files, err := ioutil.ReadDir(historyDir)
|
||||||
return
|
if err != nil {
|
||||||
}
|
http.Error(w, "Could not read history", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
var history []QueryResult
|
var history []QueryResult
|
||||||
for _, file := range files {
|
for _, file := range files {
|
||||||
if filepath.Ext(file.Name()) == ".json" {
|
if filepath.Ext(file.Name()) == ".json" {
|
||||||
data, err := ioutil.ReadFile(filepath.Join(historyDir, file.Name()))
|
data, err := ioutil.ReadFile(filepath.Join(historyDir, file.Name()))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
var qr QueryResult
|
var qr QueryResult
|
||||||
if err := json.Unmarshal(data, &qr); err == nil {
|
if err := json.Unmarshal(data, &qr); err == nil {
|
||||||
history = append(history, qr)
|
history = append(history, qr)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sort by timestamp, oldest first
|
||||||
|
sort.Slice(history, func(i, j int) bool {
|
||||||
|
return history[i].Timestamp < history[j].Timestamp
|
||||||
|
})
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(history)
|
||||||
|
|
||||||
|
case http.MethodDelete:
|
||||||
|
id := strings.TrimPrefix(r.URL.Path, "/history/")
|
||||||
|
if id == "" {
|
||||||
|
http.Error(w, "History ID is required", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Basic sanitization to prevent directory traversal
|
||||||
|
cleanID := filepath.Base(id)
|
||||||
|
if cleanID != id || strings.Contains(cleanID, "..") {
|
||||||
|
http.Error(w, "Invalid history ID", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
filePath := filepath.Join(historyDir, cleanID+".json")
|
||||||
|
|
||||||
|
if _, err := os.Stat(filePath); os.IsNotExist(err) {
|
||||||
|
http.Error(w, "History item not found", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.Remove(filePath); err != nil {
|
||||||
|
log.Printf("Failed to delete history file %s: %v", filePath, err)
|
||||||
|
http.Error(w, "Failed to delete history item", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
|
||||||
|
default:
|
||||||
|
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sort by timestamp, oldest first
|
|
||||||
sort.Slice(history, func(i, j int) bool {
|
|
||||||
return history[i].Timestamp < history[j].Timestamp
|
|
||||||
})
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
json.NewEncoder(w).Encode(history)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleQuery(w http.ResponseWriter, r *http.Request) {
|
func handleQuery(w http.ResponseWriter, r *http.Request) {
|
||||||
@ -133,7 +176,8 @@ func handleQuery(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
query := strings.TrimSpace(req.Query)
|
query := strings.TrimSpace(req.Query)
|
||||||
isSelect := strings.HasPrefix(strings.ToLower(query), "select") || strings.HasPrefix(strings.ToLower(query), "show") || strings.HasPrefix(strings.ToLower(query), "describe")
|
query_lower := strings.ToLower(query)
|
||||||
|
isSelect := strings.HasPrefix(query_lower, "select") || strings.HasPrefix(query_lower, "show") || strings.HasPrefix(query_lower, "describe") || strings.HasPrefix(query_lower, "desc")
|
||||||
|
|
||||||
result := QueryResult{
|
result := QueryResult{
|
||||||
ID: req.ID,
|
ID: req.ID,
|
||||||
@ -141,10 +185,12 @@ func handleQuery(w http.ResponseWriter, r *http.Request) {
|
|||||||
Timestamp: time.Now().UnixNano(),
|
Timestamp: time.Now().UnixNano(),
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate new ID if it's a new query
|
// Generate new ID if it's a new query
|
||||||
if result.ID == "" {
|
if result.ID == "" {
|
||||||
result.ID = strconv.FormatInt(result.Timestamp, 10)
|
result.ID = strconv.FormatInt(result.Timestamp, 10)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
startTime := time.Now()
|
||||||
|
|
||||||
if isSelect {
|
if isSelect {
|
||||||
// It's a query that returns rows
|
// It's a query that returns rows
|
||||||
@ -155,21 +201,21 @@ func handleQuery(w http.ResponseWriter, r *http.Request) {
|
|||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
cols, _ := rows.Columns()
|
cols, _ := rows.Columns()
|
||||||
result.Columns = cols
|
result.Columns = cols
|
||||||
|
|
||||||
for rows.Next() {
|
|
||||||
// Create a slice of interface{}'s to represent a row
|
|
||||||
columns := make([]interface{}, len(cols))
|
|
||||||
columnPointers := make([]interface{}, len(cols))
|
|
||||||
for i := range columns {
|
|
||||||
columnPointers[i] = &columns[i]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Scan the result into the column pointers...
|
for rows.Next() {
|
||||||
if err := rows.Scan(columnPointers...); err != nil {
|
// Create a slice of interface{}'s to represent a row
|
||||||
result.Error = err.Error()
|
columns := make([]interface{}, len(cols))
|
||||||
break
|
columnPointers := make([]interface{}, len(cols))
|
||||||
}
|
for i := range columns {
|
||||||
|
columnPointers[i] = &columns[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scan the result into the column pointers...
|
||||||
|
if err := rows.Scan(columnPointers...); err != nil {
|
||||||
|
result.Error = err.Error()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
// Convert byte slices to strings for better JSON representation
|
// Convert byte slices to strings for better JSON representation
|
||||||
for i, col := range columns {
|
for i, col := range columns {
|
||||||
if b, ok := col.([]byte); ok {
|
if b, ok := col.([]byte); ok {
|
||||||
@ -177,7 +223,7 @@ func handleQuery(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
result.Rows = append(result.Rows, columns)
|
result.Rows = append(result.Rows, columns)
|
||||||
}
|
}
|
||||||
if err := rows.Err(); err != nil {
|
if err := rows.Err(); err != nil {
|
||||||
result.Error = err.Error()
|
result.Error = err.Error()
|
||||||
@ -198,6 +244,8 @@ func handleQuery(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
result.Duration = time.Since(startTime).Milliseconds()
|
||||||
|
|
||||||
// Save to history
|
// Save to history
|
||||||
filePath := filepath.Join(historyDir, result.ID+".json")
|
filePath := filepath.Join(historyDir, result.ID+".json")
|
||||||
fileData, _ := json.MarshalIndent(result, "", " ")
|
fileData, _ := json.MarshalIndent(result, "", " ")
|
||||||
@ -208,4 +256,4 @@ func handleQuery(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
json.NewEncoder(w).Encode(result)
|
json.NewEncoder(w).Encode(result)
|
||||||
}
|
}
|
||||||
|
|||||||
251
index.html
251
index.html
@ -6,9 +6,32 @@
|
|||||||
<title>dbPrompt</title>
|
<title>dbPrompt</title>
|
||||||
<style>
|
<style>
|
||||||
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; margin: 0; background-color: #f0f2f5; color: #1c1e21; }
|
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; margin: 0; background-color: #f0f2f5; color: #1c1e21; }
|
||||||
header { background-color: #ffffff; padding: 10px 20px; border-bottom: 1px solid #dddfe2; font-size: 24px; font-weight: bold; color: #4b4f56; }
|
header {
|
||||||
|
background-color: #ffffff; padding: 10px 20px; border-bottom: 1px solid #dddfe2; font-size: 24px; font-weight: bold; color: #4b4f56;
|
||||||
|
display: flex; justify-content: space-between; align-items: center;
|
||||||
|
}
|
||||||
|
.header-logo {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
.header-logo a,
|
||||||
|
.header-logo a:visited {
|
||||||
|
text-decoration: none;
|
||||||
|
color: #4b4f56;
|
||||||
|
}
|
||||||
|
.header-buttons button {
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: bold;
|
||||||
|
padding: 8px 12px;
|
||||||
|
margin-left: 10px;
|
||||||
|
border: 1px solid #ccd0d5;
|
||||||
|
border-radius: 6px;
|
||||||
|
background-color: #f5f6f7;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.header-buttons button:hover { background-color: #e9ebee; }
|
||||||
main { padding: 20px; }
|
main { padding: 20px; }
|
||||||
.query-block { background-color: #ffffff; border: 1px solid #dddfe2; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 1px 2px rgba(0,0,0,0.1); }
|
.query-block { background-color: #ffffff; border: 1px solid #dddfe2; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 1px 2px rgba(0,0,0,0.1); overflow: hidden; }
|
||||||
.query-input { padding: 12px; }
|
.query-input { padding: 12px; }
|
||||||
textarea { width: 100%; box-sizing: border-box; border: 1px solid #ccd0d5; border-radius: 6px; padding: 12px; font-family: "Courier New", Courier, monospace; font-size: 14px; resize: vertical; min-height: 80px; }
|
textarea { width: 100%; box-sizing: border-box; border: 1px solid #ccd0d5; border-radius: 6px; padding: 12px; font-family: "Courier New", Courier, monospace; font-size: 14px; resize: vertical; min-height: 80px; }
|
||||||
.run-button {
|
.run-button {
|
||||||
@ -16,19 +39,65 @@
|
|||||||
transition: background-color 0.2s;
|
transition: background-color 0.2s;
|
||||||
}
|
}
|
||||||
.run-button:hover { background-color: #166fe5; }
|
.run-button:hover { background-color: #166fe5; }
|
||||||
.result-container { padding: 0 12px 12px 12px; }
|
.delete-button {
|
||||||
.result-container .error { color: #fa383e; background-color: #ffe5e6; padding: 10px; border-radius: 6px; white-space: pre-wrap; word-break: break-all; }
|
background-color: #fa383e; color: white; border: none; padding: 10px 15px; border-radius: 6px; font-weight: bold; cursor: pointer; margin-top: 10px; margin-left: 5px;
|
||||||
.result-container .info { color: #117a11; background-color: #e6f6e6; padding: 10px; border-radius: 6px; }
|
transition: background-color 0.2s;
|
||||||
table { border-collapse: collapse; width: 100%; margin-top: 12px; }
|
}
|
||||||
|
.delete-button:hover { background-color: #e02c33; }
|
||||||
|
.result-container .error { margin: 12px; color: #fa383e; background-color: #ffe5e6; padding: 10px; border-radius: 6px; white-space: pre-wrap; word-break: break-all; }
|
||||||
|
.result-container .info { margin: 12px; color: #117a11; background-color: #e6f6e6; padding: 10px; border-radius: 6px; }
|
||||||
|
.result-meta {
|
||||||
|
padding: 8px 12px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #606770;
|
||||||
|
background-color: #f5f6f7;
|
||||||
|
border-top: 1px solid #dddfe2;
|
||||||
|
}
|
||||||
|
table { border-collapse: collapse; width: 100%; }
|
||||||
th, td { border: 1px solid #dddfe2; padding: 8px; text-align: left; vertical-align: top; }
|
th, td { border: 1px solid #dddfe2; padding: 8px; text-align: left; vertical-align: top; }
|
||||||
th { background-color: #f5f6f7; font-weight: bold; }
|
th { background-color: #f5f6f7; font-weight: bold; }
|
||||||
tbody tr:nth-child(odd) { background-color: #f9f9f9; }
|
tbody tr:nth-child(odd) { background-color: #f9f9f9; }
|
||||||
|
|
||||||
|
.collapsible-header {
|
||||||
|
background-color: #f5f6f7;
|
||||||
|
padding: 10px 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
border-top: 1px solid #dddfe2;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
.collapsible-header:hover { background-color: #e9ebee; }
|
||||||
|
.toggle-icon {
|
||||||
|
margin-right: 8px;
|
||||||
|
font-family: monospace;
|
||||||
|
font-size: 14px;
|
||||||
|
width: 12px;
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
.collapsible-content {
|
||||||
|
padding: 12px;
|
||||||
|
border-top: 1px solid #dddfe2;
|
||||||
|
}
|
||||||
|
.collapsible-content.collapsed {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|
||||||
<header>dbPrompt</header>
|
<header>
|
||||||
|
<div class="header-logo">
|
||||||
|
<a href="https://www.tpsoft.org" target="_blank"><img src="static/tpsoft-logo.png" alt="TPsoft.org" height="59"></a>
|
||||||
|
<a href="index.html">dbPrompt</a>
|
||||||
|
</div>
|
||||||
|
<div class="header-buttons">
|
||||||
|
<button id="collapse-all-btn">Collapse All</button>
|
||||||
|
<button id="expand-all-btn">Expand All</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
<main id="main-container">
|
<main id="main-container">
|
||||||
<!-- Query blocks will be inserted here -->
|
<!-- Query blocks will be inserted here -->
|
||||||
</main>
|
</main>
|
||||||
@ -36,11 +105,37 @@
|
|||||||
<script>
|
<script>
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
const mainContainer = document.getElementById('main-container');
|
const mainContainer = document.getElementById('main-container');
|
||||||
|
const collapseAllBtn = document.getElementById('collapse-all-btn');
|
||||||
|
const expandAllBtn = document.getElementById('expand-all-btn');
|
||||||
|
|
||||||
|
// --- Global Action Handlers ---
|
||||||
|
collapseAllBtn.addEventListener('click', () => {
|
||||||
|
document.querySelectorAll('.collapsible-content').forEach(content => {
|
||||||
|
content.classList.add('collapsed');
|
||||||
|
const header = content.previousElementSibling;
|
||||||
|
if (header && header.classList.contains('collapsible-header')) {
|
||||||
|
header.querySelector('.toggle-icon').textContent = '►';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
expandAllBtn.addEventListener('click', () => {
|
||||||
|
document.querySelectorAll('.collapsible-content').forEach(content => {
|
||||||
|
content.classList.remove('collapsed');
|
||||||
|
const header = content.previousElementSibling;
|
||||||
|
if (header && header.classList.contains('collapsible-header')) {
|
||||||
|
header.querySelector('.toggle-icon').textContent = '▼';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// --- Main Event Handler ---
|
// --- Main Event Handler ---
|
||||||
mainContainer.addEventListener('click', async (e) => {
|
mainContainer.addEventListener('click', async (e) => {
|
||||||
if (e.target.classList.contains('run-button')) {
|
const target = e.target;
|
||||||
const block = e.target.closest('.query-block');
|
|
||||||
|
// Handle Run Query
|
||||||
|
if (target.classList.contains('run-button')) {
|
||||||
|
const block = target.closest('.query-block');
|
||||||
const textarea = block.querySelector('textarea');
|
const textarea = block.querySelector('textarea');
|
||||||
const queryId = block.dataset.id || '';
|
const queryId = block.dataset.id || '';
|
||||||
const query = textarea.value.trim();
|
const query = textarea.value.trim();
|
||||||
@ -57,76 +152,140 @@
|
|||||||
body: JSON.stringify({ id: queryId, query: query })
|
body: JSON.stringify({ id: queryId, query: query })
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
|
||||||
throw new Error(`HTTP error! Status: ${response.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
const isNewQueryBlock = block.classList.contains('new-query-block');
|
||||||
// If it was a new query, update its block with the new ID
|
|
||||||
const wasNewQuery = !block.dataset.id;
|
|
||||||
block.dataset.id = data.id;
|
|
||||||
|
|
||||||
|
block.dataset.id = data.id;
|
||||||
renderResult(resultContainer, data);
|
renderResult(resultContainer, data);
|
||||||
|
|
||||||
// If it was a successful new query, add another blank input
|
if (isNewQueryBlock && !data.error) {
|
||||||
if (wasNewQuery && !data.error) {
|
block.classList.remove('new-query-block');
|
||||||
addQueryBlock();
|
const deleteButton = document.createElement('button');
|
||||||
|
deleteButton.className = 'delete-button';
|
||||||
|
deleteButton.textContent = 'Delete';
|
||||||
|
block.querySelector('.query-input').appendChild(deleteButton);
|
||||||
|
addQueryBlock({}, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
renderResult(resultContainer, { error: error.message });
|
renderResult(resultContainer, { error: error.message });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handle Delete Query
|
||||||
|
if (target.classList.contains('delete-button')) {
|
||||||
|
if (confirm('Are you sure you want to delete this query history item?')) {
|
||||||
|
const block = target.closest('.query-block');
|
||||||
|
const queryId = block.dataset.id;
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/history/${queryId}`, { method: 'DELETE' });
|
||||||
|
if (!response.ok) {
|
||||||
|
const errorText = await response.text();
|
||||||
|
throw new Error(`HTTP error! Status: ${response.status} - ${errorText}`);
|
||||||
|
}
|
||||||
|
block.remove();
|
||||||
|
} catch (error) {
|
||||||
|
const resultContainer = block.querySelector('.result-container');
|
||||||
|
renderResult(resultContainer, { error: `Failed to delete: ${error.message}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle Toggle Collapse
|
||||||
|
const header = target.closest('.collapsible-header');
|
||||||
|
if (header) {
|
||||||
|
const content = header.nextElementSibling;
|
||||||
|
if (content && content.classList.contains('collapsible-content')) {
|
||||||
|
content.classList.toggle('collapsed');
|
||||||
|
const icon = header.querySelector('.toggle-icon');
|
||||||
|
icon.textContent = content.classList.contains('collapsed') ? '►' : '▼';
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// --- Rendering Functions ---
|
// --- Rendering Functions ---
|
||||||
function renderResult(container, data) {
|
function renderResult(container, data) {
|
||||||
let html = '';
|
let contentHtml = '';
|
||||||
|
let isCollapsible = false;
|
||||||
|
|
||||||
if (data.error) {
|
if (data.error) {
|
||||||
html = `<div class="error">${escapeHtml(data.error)}</div>`;
|
contentHtml = `<div class="error">${escapeHtml(data.error)}</div>`;
|
||||||
} else if (data.columns && data.rows) {
|
} else if (data.columns && data.rows) {
|
||||||
// SELECT, SHOW, etc.
|
|
||||||
if (data.rows.length === 0) {
|
if (data.rows.length === 0) {
|
||||||
html = `<div class="info">Query executed successfully. 0 rows returned.</div>`;
|
contentHtml = `<div class="info">Query executed successfully. 0 rows returned.</div>`;
|
||||||
} else {
|
} else {
|
||||||
html = '<table><thead><tr>';
|
isCollapsible = true;
|
||||||
data.columns.forEach(col => html += `<th>${escapeHtml(col)}</th>`);
|
let tableHtml = '<table><thead><tr>';
|
||||||
html += '</tr></thead><tbody>';
|
data.columns.forEach(col => tableHtml += `<th>${escapeHtml(col)}</th>`);
|
||||||
|
tableHtml += '</tr></thead><tbody>';
|
||||||
data.rows.forEach(row => {
|
data.rows.forEach(row => {
|
||||||
html += '<tr>';
|
tableHtml += '<tr>';
|
||||||
row.forEach(cell => {
|
row.forEach(cell => {
|
||||||
html += `<td>${escapeHtml(cell === null ? 'NULL' : cell)}</td>`;
|
tableHtml += `<td>${escapeHtml(cell === null ? 'NULL' : cell)}</td>`;
|
||||||
});
|
});
|
||||||
html += '</tr>';
|
tableHtml += '</tr>';
|
||||||
});
|
});
|
||||||
html += '</tbody></table>';
|
tableHtml += '</tbody></table>';
|
||||||
|
contentHtml = tableHtml;
|
||||||
}
|
}
|
||||||
} else if (data.hasOwnProperty('rowsAffected')) {
|
} else if (data.hasOwnProperty('rowsAffected')) {
|
||||||
// INSERT, UPDATE, DELETE
|
contentHtml = `<div class="info">Query executed successfully. ${data.rowsAffected} rows affected.</div>`;
|
||||||
html = `<div class="info">Query executed successfully. ${data.rowsAffected} rows affected.</div>`;
|
} else if (!data.error) {
|
||||||
} else {
|
contentHtml = `<div class="info">Query executed successfully.</div>`;
|
||||||
html = `<div class="info">Query executed. No rows returned.</div>`;
|
|
||||||
}
|
}
|
||||||
container.innerHTML = html;
|
|
||||||
|
let metaHtml = '';
|
||||||
|
if (data.timestamp) {
|
||||||
|
metaHtml = `
|
||||||
|
<div class="result-meta">
|
||||||
|
<span>Executed: ${new Date(data.timestamp / 1000000).toLocaleString()}</span> |
|
||||||
|
<span>Duration: ${data.duration ?? 'N/A'} ms</span>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
let finalHtml;
|
||||||
|
if (isCollapsible) {
|
||||||
|
finalHtml = `
|
||||||
|
<div class="collapsible-header">
|
||||||
|
<span class="toggle-icon">▼</span>
|
||||||
|
Result (${data.rows.length} rows)
|
||||||
|
</div>
|
||||||
|
<div class="collapsible-content">
|
||||||
|
${contentHtml}
|
||||||
|
</div>
|
||||||
|
${metaHtml}
|
||||||
|
`;
|
||||||
|
} else {
|
||||||
|
finalHtml = contentHtml + metaHtml;
|
||||||
|
}
|
||||||
|
|
||||||
|
container.innerHTML = finalHtml;
|
||||||
}
|
}
|
||||||
|
|
||||||
function addQueryBlock(data = {}) {
|
function addQueryBlock(data = {}, isNew = false) {
|
||||||
const block = document.createElement('div');
|
const block = document.createElement('div');
|
||||||
block.className = 'query-block';
|
block.className = 'query-block';
|
||||||
if (data.id) {
|
if (data.id) {
|
||||||
block.dataset.id = data.id;
|
block.dataset.id = data.id;
|
||||||
}
|
}
|
||||||
|
if (isNew) {
|
||||||
|
block.classList.add('new-query-block');
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleteButtonHtml = !isNew ? `<button class="delete-button">Delete</button>` : '';
|
||||||
|
|
||||||
block.innerHTML = `
|
block.innerHTML = `
|
||||||
<div class="query-input">
|
<div class="query-input">
|
||||||
<textarea placeholder="Enter your SQL query here...">${data.query ? escapeHtml(data.query) : ''}</textarea>
|
<textarea placeholder="Enter your SQL query here...">${data.query ? escapeHtml(data.query) : ''}</textarea>
|
||||||
<button class="run-button">Run Query</button>
|
<button class="run-button">Run Query</button>
|
||||||
|
${deleteButtonHtml}
|
||||||
</div>
|
</div>
|
||||||
<div class="result-container"></div>
|
<div class="result-container"></div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
if (data.id) { // Only render previous results if they exist
|
if (data.id) {
|
||||||
const resultContainer = block.querySelector('.result-container');
|
const resultContainer = block.querySelector('.result-container');
|
||||||
renderResult(resultContainer, data);
|
renderResult(resultContainer, data);
|
||||||
}
|
}
|
||||||
@ -138,21 +297,16 @@
|
|||||||
// --- Initialization ---
|
// --- Initialization ---
|
||||||
async function loadHistory() {
|
async function loadHistory() {
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/history');
|
const response = await fetch('/history/');
|
||||||
if (!response.ok) throw new Error('Failed to load history.');
|
if (!response.ok) throw new Error('Failed to load history.');
|
||||||
|
|
||||||
const history = await response.json();
|
const history = await response.json();
|
||||||
|
|
||||||
if (history && history.length > 0) {
|
if (history && history.length > 0) {
|
||||||
history.forEach(item => addQueryBlock(item));
|
history.forEach(item => addQueryBlock(item, false));
|
||||||
}
|
}
|
||||||
|
addQueryBlock({}, true);
|
||||||
// Always have at least one empty block
|
|
||||||
addQueryBlock();
|
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
const block = addQueryBlock();
|
const block = addQueryBlock({}, true);
|
||||||
const resultContainer = block.querySelector('.result-container');
|
const resultContainer = block.querySelector('.result-container');
|
||||||
renderResult(resultContainer, { error: 'Could not load history from server. You can still run new queries.' });
|
renderResult(resultContainer, { error: 'Could not load history from server. You can still run new queries.' });
|
||||||
}
|
}
|
||||||
@ -160,6 +314,7 @@
|
|||||||
|
|
||||||
// --- Utilities ---
|
// --- Utilities ---
|
||||||
function escapeHtml(str) {
|
function escapeHtml(str) {
|
||||||
|
if (str === null || str === undefined) return '';
|
||||||
const p = document.createElement('p');
|
const p = document.createElement('p');
|
||||||
p.textContent = str;
|
p.textContent = str;
|
||||||
return p.innerHTML;
|
return p.innerHTML;
|
||||||
|
|||||||
BIN
static/tpsoft-logo.png
Normal file
BIN
static/tpsoft-logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 9.8 KiB |
Reference in New Issue
Block a user