first version of dbPrompt = basic usage
This commit is contained in:
211
dbPrompt.go
Normal file
211
dbPrompt.go
Normal file
@ -0,0 +1,211 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io/ioutil"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
_ "github.com/go-sql-driver/mysql"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config struct for database connection
|
||||||
|
type Config struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
Hostname string `json:"hostname"`
|
||||||
|
Port int `json:"port"`
|
||||||
|
Database string `json:"database"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueryRequest from the frontend
|
||||||
|
type QueryRequest struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Query string `json:"query"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueryResult represents a single historical query execution
|
||||||
|
type QueryResult struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Query string `json:"query"`
|
||||||
|
Timestamp int64 `json:"timestamp"`
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
Columns []string `json:"columns,omitempty"`
|
||||||
|
Rows [][]interface{} `json:"rows,omitempty"`
|
||||||
|
RowsAffected int64 `json:"rowsAffected,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var db *sql.DB
|
||||||
|
var historyDir = "./history"
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Load configuration
|
||||||
|
file, err := os.Open("config.json")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to open config file: %v", err)
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
var config Config
|
||||||
|
decoder := json.NewDecoder(file)
|
||||||
|
if err := decoder.Decode(&config); err != nil {
|
||||||
|
log.Fatalf("Failed to decode config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connect to the database
|
||||||
|
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true",
|
||||||
|
config.Username, config.Password, config.Hostname, config.Port, config.Database)
|
||||||
|
db, err = sql.Open("mysql", dsn)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to open database connection: %v", err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
if err := db.Ping(); err != nil {
|
||||||
|
log.Fatalf("Failed to connect to the database: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("Successfully connected to the database.")
|
||||||
|
|
||||||
|
// Ensure history directory exists
|
||||||
|
if _, err := os.Stat(historyDir); os.IsNotExist(err) {
|
||||||
|
os.Mkdir(historyDir, 0755)
|
||||||
|
}
|
||||||
|
|
||||||
|
// HTTP Handlers
|
||||||
|
http.HandleFunc("/", serveIndex)
|
||||||
|
http.HandleFunc("/query", handleQuery)
|
||||||
|
http.HandleFunc("/history", handleHistory)
|
||||||
|
|
||||||
|
log.Println("Starting server on :8080...")
|
||||||
|
if err := http.ListenAndServe(":8080", nil); err != nil {
|
||||||
|
log.Fatalf("Server failed: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func serveIndex(w http.ResponseWriter, r *http.Request) {
|
||||||
|
http.ServeFile(w, r, "index.html")
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleHistory(w http.ResponseWriter, r *http.Request) {
|
||||||
|
files, err := ioutil.ReadDir(historyDir)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Could not read history", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var history []QueryResult
|
||||||
|
for _, file := range files {
|
||||||
|
if filepath.Ext(file.Name()) == ".json" {
|
||||||
|
data, err := ioutil.ReadFile(filepath.Join(historyDir, file.Name()))
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var qr QueryResult
|
||||||
|
if err := json.Unmarshal(data, &qr); err == nil {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleQuery(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req QueryRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
query := strings.TrimSpace(req.Query)
|
||||||
|
isSelect := strings.HasPrefix(strings.ToLower(query), "select") || strings.HasPrefix(strings.ToLower(query), "show") || strings.HasPrefix(strings.ToLower(query), "describe")
|
||||||
|
|
||||||
|
result := QueryResult{
|
||||||
|
ID: req.ID,
|
||||||
|
Query: req.Query,
|
||||||
|
Timestamp: time.Now().UnixNano(),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate new ID if it's a new query
|
||||||
|
if result.ID == "" {
|
||||||
|
result.ID = strconv.FormatInt(result.Timestamp, 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
if isSelect {
|
||||||
|
// It's a query that returns rows
|
||||||
|
rows, err := db.Query(query)
|
||||||
|
if err != nil {
|
||||||
|
result.Error = err.Error()
|
||||||
|
} else {
|
||||||
|
defer rows.Close()
|
||||||
|
cols, _ := rows.Columns()
|
||||||
|
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...
|
||||||
|
if err := rows.Scan(columnPointers...); err != nil {
|
||||||
|
result.Error = err.Error()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert byte slices to strings for better JSON representation
|
||||||
|
for i, col := range columns {
|
||||||
|
if b, ok := col.([]byte); ok {
|
||||||
|
columns[i] = string(b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result.Rows = append(result.Rows, columns)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
result.Error = err.Error()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// It's a statement like INSERT, UPDATE, DELETE
|
||||||
|
res, err := db.Exec(query)
|
||||||
|
if err != nil {
|
||||||
|
result.Error = err.Error()
|
||||||
|
} else {
|
||||||
|
affected, err := res.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
result.Error = err.Error()
|
||||||
|
} else {
|
||||||
|
result.RowsAffected = affected
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save to history
|
||||||
|
filePath := filepath.Join(historyDir, result.ID+".json")
|
||||||
|
fileData, _ := json.MarshalIndent(result, "", " ")
|
||||||
|
if err := ioutil.WriteFile(filePath, fileData, 0644); err != nil {
|
||||||
|
log.Printf("Failed to write history file %s: %v", filePath, err)
|
||||||
|
// Don't send a server error back to client, they can still see the result
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(result)
|
||||||
|
}
|
||||||
8
go.mod
Normal file
8
go.mod
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
module dbPrompt
|
||||||
|
|
||||||
|
go 1.23.2
|
||||||
|
|
||||||
|
require (
|
||||||
|
filippo.io/edwards25519 v1.1.0 // indirect
|
||||||
|
github.com/go-sql-driver/mysql v1.9.3 // indirect
|
||||||
|
)
|
||||||
4
go.sum
Normal file
4
go.sum
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||||
|
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||||
|
github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
|
||||||
|
github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
|
||||||
173
index.html
Normal file
173
index.html
Normal file
@ -0,0 +1,173 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>dbPrompt</title>
|
||||||
|
<style>
|
||||||
|
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; }
|
||||||
|
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-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; }
|
||||||
|
.run-button {
|
||||||
|
background-color: #1877f2; color: white; border: none; padding: 10px 15px; border-radius: 6px; font-weight: bold; cursor: pointer; margin-top: 10px;
|
||||||
|
transition: background-color 0.2s;
|
||||||
|
}
|
||||||
|
.run-button:hover { background-color: #166fe5; }
|
||||||
|
.result-container { padding: 0 12px 12px 12px; }
|
||||||
|
.result-container .error { color: #fa383e; background-color: #ffe5e6; padding: 10px; border-radius: 6px; white-space: pre-wrap; word-break: break-all; }
|
||||||
|
.result-container .info { color: #117a11; background-color: #e6f6e6; padding: 10px; border-radius: 6px; }
|
||||||
|
table { border-collapse: collapse; width: 100%; margin-top: 12px; }
|
||||||
|
th, td { border: 1px solid #dddfe2; padding: 8px; text-align: left; vertical-align: top; }
|
||||||
|
th { background-color: #f5f6f7; font-weight: bold; }
|
||||||
|
tbody tr:nth-child(odd) { background-color: #f9f9f9; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<header>dbPrompt</header>
|
||||||
|
|
||||||
|
<main id="main-container">
|
||||||
|
<!-- Query blocks will be inserted here -->
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
const mainContainer = document.getElementById('main-container');
|
||||||
|
|
||||||
|
// --- Main Event Handler ---
|
||||||
|
mainContainer.addEventListener('click', async (e) => {
|
||||||
|
if (e.target.classList.contains('run-button')) {
|
||||||
|
const block = e.target.closest('.query-block');
|
||||||
|
const textarea = block.querySelector('textarea');
|
||||||
|
const queryId = block.dataset.id || '';
|
||||||
|
const query = textarea.value.trim();
|
||||||
|
|
||||||
|
if (!query) return;
|
||||||
|
|
||||||
|
const resultContainer = block.querySelector('.result-container');
|
||||||
|
resultContainer.innerHTML = '<div class="info">Executing...</div>';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/query', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ id: queryId, query: query })
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP error! Status: ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
// If it was a new query, update its block with the new ID
|
||||||
|
const wasNewQuery = !block.dataset.id;
|
||||||
|
block.dataset.id = data.id;
|
||||||
|
|
||||||
|
renderResult(resultContainer, data);
|
||||||
|
|
||||||
|
// If it was a successful new query, add another blank input
|
||||||
|
if (wasNewQuery && !data.error) {
|
||||||
|
addQueryBlock();
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
renderResult(resultContainer, { error: error.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// --- Rendering Functions ---
|
||||||
|
function renderResult(container, data) {
|
||||||
|
let html = '';
|
||||||
|
if (data.error) {
|
||||||
|
html = `<div class="error">${escapeHtml(data.error)}</div>`;
|
||||||
|
} else if (data.columns && data.rows) {
|
||||||
|
// SELECT, SHOW, etc.
|
||||||
|
if (data.rows.length === 0) {
|
||||||
|
html = `<div class="info">Query executed successfully. 0 rows returned.</div>`;
|
||||||
|
} else {
|
||||||
|
html = '<table><thead><tr>';
|
||||||
|
data.columns.forEach(col => html += `<th>${escapeHtml(col)}</th>`);
|
||||||
|
html += '</tr></thead><tbody>';
|
||||||
|
data.rows.forEach(row => {
|
||||||
|
html += '<tr>';
|
||||||
|
row.forEach(cell => {
|
||||||
|
html += `<td>${escapeHtml(cell === null ? 'NULL' : cell)}</td>`;
|
||||||
|
});
|
||||||
|
html += '</tr>';
|
||||||
|
});
|
||||||
|
html += '</tbody></table>';
|
||||||
|
}
|
||||||
|
} else if (data.hasOwnProperty('rowsAffected')) {
|
||||||
|
// INSERT, UPDATE, DELETE
|
||||||
|
html = `<div class="info">Query executed successfully. ${data.rowsAffected} rows affected.</div>`;
|
||||||
|
} else {
|
||||||
|
html = `<div class="info">Query executed. No rows returned.</div>`;
|
||||||
|
}
|
||||||
|
container.innerHTML = html;
|
||||||
|
}
|
||||||
|
|
||||||
|
function addQueryBlock(data = {}) {
|
||||||
|
const block = document.createElement('div');
|
||||||
|
block.className = 'query-block';
|
||||||
|
if (data.id) {
|
||||||
|
block.dataset.id = data.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
block.innerHTML = `
|
||||||
|
<div class="query-input">
|
||||||
|
<textarea placeholder="Enter your SQL query here...">${data.query ? escapeHtml(data.query) : ''}</textarea>
|
||||||
|
<button class="run-button">Run Query</button>
|
||||||
|
</div>
|
||||||
|
<div class="result-container"></div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
if (data.id) { // Only render previous results if they exist
|
||||||
|
const resultContainer = block.querySelector('.result-container');
|
||||||
|
renderResult(resultContainer, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
mainContainer.appendChild(block);
|
||||||
|
return block;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Initialization ---
|
||||||
|
async function loadHistory() {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/history');
|
||||||
|
if (!response.ok) throw new Error('Failed to load history.');
|
||||||
|
|
||||||
|
const history = await response.json();
|
||||||
|
|
||||||
|
if (history && history.length > 0) {
|
||||||
|
history.forEach(item => addQueryBlock(item));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Always have at least one empty block
|
||||||
|
addQueryBlock();
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
const block = addQueryBlock();
|
||||||
|
const resultContainer = block.querySelector('.result-container');
|
||||||
|
renderResult(resultContainer, { error: 'Could not load history from server. You can still run new queries.' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Utilities ---
|
||||||
|
function escapeHtml(str) {
|
||||||
|
const p = document.createElement('p');
|
||||||
|
p.textContent = str;
|
||||||
|
return p.innerHTML;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Start the app ---
|
||||||
|
loadHistory();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in New Issue
Block a user