2
0

handler.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. package httpserver
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "log"
  7. "net/http"
  8. "strings"
  9. "sync/atomic"
  10. "time"
  11. "github.com/danfragoso/pizzasql-next/pkg/csvexport"
  12. "github.com/danfragoso/pizzasql-next/pkg/csvimport"
  13. "github.com/danfragoso/pizzasql-next/pkg/lexer"
  14. "github.com/danfragoso/pizzasql-next/pkg/parser"
  15. "github.com/danfragoso/pizzasql-next/pkg/sqlexport"
  16. "github.com/danfragoso/pizzasql-next/pkg/sqlimport"
  17. )
  18. // QueryRequest represents a single query request.
  19. type QueryRequest struct {
  20. SQL string `json:"sql"`
  21. Params []interface{} `json:"params"`
  22. }
  23. // ExecuteRequest represents a batch execution request.
  24. type ExecuteRequest struct {
  25. Statements []QueryRequest `json:"statements"`
  26. Transaction bool `json:"transaction"`
  27. }
  28. // TransactionRequest represents a transaction management request.
  29. type TransactionRequest struct {
  30. TransactionID string `json:"transactionId"`
  31. }
  32. // handleQuery handles POST /query
  33. func (s *Server) handleQuery(w http.ResponseWriter, r *http.Request) {
  34. if r.Method != http.MethodPost {
  35. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  36. return
  37. }
  38. var req QueryRequest
  39. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  40. writeError(w, http.StatusBadRequest, "INVALID_JSON", "Invalid JSON in request body", nil)
  41. return
  42. }
  43. if req.SQL == "" {
  44. writeError(w, http.StatusBadRequest, "MISSING_SQL", "SQL query is required", nil)
  45. return
  46. }
  47. // Get database from X-Database header
  48. dbName := r.Header.Get("X-Database")
  49. exec, _, err := s.getExecutorForDatabase(dbName)
  50. if err != nil {
  51. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  52. return
  53. }
  54. // Check for pretty print
  55. pretty := r.URL.Query().Get("pretty") == "true"
  56. explain := r.URL.Query().Get("explain") == "true"
  57. readonly := r.URL.Query().Get("readonly") == "true"
  58. // Parse timeout
  59. timeout := 5 * time.Minute
  60. if t := r.URL.Query().Get("timeout"); t != "" {
  61. if d, err := time.ParseDuration(t); err == nil {
  62. timeout = d
  63. }
  64. }
  65. // Execute with timeout
  66. resultChan := make(chan *QueryResponse, 1)
  67. errorChan := make(chan error, 1)
  68. go func() {
  69. start := time.Now()
  70. // Check readonly mode
  71. if readonly {
  72. upper := strings.ToUpper(strings.TrimSpace(req.SQL))
  73. if strings.HasPrefix(upper, "INSERT") ||
  74. strings.HasPrefix(upper, "UPDATE") ||
  75. strings.HasPrefix(upper, "DELETE") ||
  76. strings.HasPrefix(upper, "CREATE") ||
  77. strings.HasPrefix(upper, "DROP") ||
  78. strings.HasPrefix(upper, "ALTER") {
  79. errorChan <- &HTTPError{
  80. Code: "READ_ONLY_MODE",
  81. Message: "Write operations not allowed in read-only mode",
  82. Status: http.StatusForbidden,
  83. }
  84. return
  85. }
  86. }
  87. // Substitute parameters
  88. sql := substituteParams(req.SQL, req.Params)
  89. // Parse SQL
  90. l := lexer.New(sql)
  91. p := parser.New(l)
  92. stmt, err := p.Parse()
  93. if err != nil {
  94. errorChan <- &HTTPError{
  95. Code: "SYNTAX_ERROR",
  96. Message: err.Error(),
  97. Status: http.StatusBadRequest,
  98. }
  99. return
  100. }
  101. // Execute using the database-specific executor
  102. result, err := exec.Execute(stmt)
  103. if err != nil {
  104. errorChan <- &HTTPError{
  105. Code: "EXECUTION_ERROR",
  106. Message: err.Error(),
  107. Status: http.StatusInternalServerError,
  108. }
  109. return
  110. }
  111. duration := time.Since(start)
  112. // Build response
  113. resp := &QueryResponse{
  114. Columns: make([]ColumnInfo, len(result.Columns)),
  115. Rows: result.Rows,
  116. RowsAffected: result.RowsAffected,
  117. LastInsertID: result.LastInsertID,
  118. ExecutionTimeMicro: duration.Microseconds(),
  119. RowsReturned: len(result.Rows),
  120. }
  121. for i, col := range result.Columns {
  122. colType := result.GetColumnType(i)
  123. // If no type info, infer from first row values
  124. if colType == "ANY" && len(result.Rows) > 0 && i < len(result.Rows[0]) {
  125. colType = inferType(result.Rows[0][i])
  126. }
  127. resp.Columns[i] = ColumnInfo{
  128. Name: col,
  129. Type: colType,
  130. }
  131. }
  132. // Calculate bytes read (approximate size of the result set)
  133. // This is the serialized JSON size of the rows data
  134. if jsonBytes, err := json.Marshal(result.Rows); err == nil {
  135. resp.BytesRead = int64(len(jsonBytes))
  136. }
  137. if explain {
  138. resp.QueryPlan = []string{"Full table scan"} // TODO: Real query plan
  139. }
  140. resultChan <- resp
  141. }()
  142. select {
  143. case resp := <-resultChan:
  144. atomic.AddInt64(&s.stats.QueriesExecuted, 1)
  145. atomic.AddInt64(&s.stats.QueriesSuccess, 1)
  146. writeJSON(w, http.StatusOK, resp, pretty)
  147. case err := <-errorChan:
  148. atomic.AddInt64(&s.stats.QueriesExecuted, 1)
  149. atomic.AddInt64(&s.stats.QueriesError, 1)
  150. if httpErr, ok := err.(*HTTPError); ok {
  151. writeError(w, httpErr.Status, httpErr.Code, httpErr.Message, httpErr.Details)
  152. } else {
  153. writeError(w, http.StatusInternalServerError, "INTERNAL_ERROR", err.Error(), nil)
  154. }
  155. case <-time.After(timeout):
  156. atomic.AddInt64(&s.stats.QueriesExecuted, 1)
  157. atomic.AddInt64(&s.stats.QueriesError, 1)
  158. writeError(w, http.StatusRequestTimeout, "TIMEOUT", "Query execution timeout", nil)
  159. }
  160. }
  161. // handleExecute handles POST /execute for batch operations
  162. func (s *Server) handleExecute(w http.ResponseWriter, r *http.Request) {
  163. if r.Method != http.MethodPost {
  164. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  165. return
  166. }
  167. var req ExecuteRequest
  168. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  169. writeError(w, http.StatusBadRequest, "INVALID_JSON", "Invalid JSON in request body", nil)
  170. return
  171. }
  172. if len(req.Statements) == 0 {
  173. writeError(w, http.StatusBadRequest, "MISSING_STATEMENTS", "At least one statement is required", nil)
  174. return
  175. }
  176. // Get database from X-Database header
  177. dbName := r.Header.Get("X-Database")
  178. exec, _, err := s.getExecutorForDatabase(dbName)
  179. if err != nil {
  180. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  181. return
  182. }
  183. pretty := r.URL.Query().Get("pretty") == "true"
  184. start := time.Now()
  185. results := make([]ExecuteResult, 0, len(req.Statements))
  186. // Start transaction if requested
  187. if req.Transaction {
  188. l := lexer.New("BEGIN")
  189. p := parser.New(l)
  190. stmt, _ := p.Parse()
  191. exec.Execute(stmt)
  192. }
  193. var executeErr error
  194. for _, stmt := range req.Statements {
  195. // Substitute parameters
  196. sql := substituteParams(stmt.SQL, stmt.Params)
  197. l := lexer.New(sql)
  198. p := parser.New(l)
  199. parsed, err := p.Parse()
  200. if err != nil {
  201. executeErr = err
  202. break
  203. }
  204. result, err := exec.Execute(parsed)
  205. if err != nil {
  206. executeErr = err
  207. break
  208. }
  209. results = append(results, ExecuteResult{
  210. RowsAffected: result.RowsAffected,
  211. LastInsertID: result.LastInsertID,
  212. })
  213. }
  214. // Handle transaction
  215. if req.Transaction {
  216. if executeErr != nil {
  217. // Rollback on error
  218. l := lexer.New("ROLLBACK")
  219. p := parser.New(l)
  220. stmt, _ := p.Parse()
  221. exec.Execute(stmt)
  222. writeError(w, http.StatusBadRequest, "TRANSACTION_ERROR", executeErr.Error(), nil)
  223. return
  224. } else {
  225. // Commit on success
  226. l := lexer.New("COMMIT")
  227. p := parser.New(l)
  228. stmt, _ := p.Parse()
  229. exec.Execute(stmt)
  230. }
  231. } else if executeErr != nil {
  232. writeError(w, http.StatusBadRequest, "EXECUTION_ERROR", executeErr.Error(), nil)
  233. return
  234. }
  235. resp := &ExecuteResponse{
  236. Results: results,
  237. ExecutionTime: time.Since(start).String(),
  238. }
  239. writeJSON(w, http.StatusOK, resp, pretty)
  240. }
  241. // handleSchemaTables handles GET /schema/tables
  242. func (s *Server) handleSchemaTables(w http.ResponseWriter, r *http.Request) {
  243. if r.Method != http.MethodGet {
  244. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only GET method is allowed", nil)
  245. return
  246. }
  247. // Get database from X-Database header (trim whitespace)
  248. dbName := strings.TrimSpace(r.Header.Get("X-Database"))
  249. // Debug: Log the header value
  250. log.Printf("[DEBUG] /schema/tables - X-Database header: %q", dbName)
  251. _, schema, err := s.getExecutorForDatabase(dbName)
  252. if err != nil {
  253. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  254. return
  255. }
  256. // Debug: Log the actual database being used
  257. actualDB := schema.GetDatabaseName()
  258. log.Printf("[DEBUG] /schema/tables - Resolved to database: %q", actualDB)
  259. tables, err := schema.ListTables()
  260. if err != nil {
  261. writeError(w, http.StatusInternalServerError, "SCHEMA_ERROR", err.Error(), nil)
  262. return
  263. }
  264. log.Printf("[DEBUG] /schema/tables - Found %d tables in database %q", len(tables), actualDB)
  265. // Include the actual database name and requested name in the response for verification
  266. resp := map[string]interface{}{
  267. "database": actualDB,
  268. "requested_database": dbName,
  269. "tables": tables,
  270. }
  271. pretty := r.URL.Query().Get("pretty") == "true"
  272. writeJSON(w, http.StatusOK, resp, pretty)
  273. }
  274. // handleSchemaTable handles GET /schema/tables/{table}
  275. func (s *Server) handleSchemaTable(w http.ResponseWriter, r *http.Request) {
  276. if r.Method != http.MethodGet {
  277. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only GET method is allowed", nil)
  278. return
  279. }
  280. // Get database from X-Database header
  281. dbName := r.Header.Get("X-Database")
  282. _, schemaManager, err := s.getExecutorForDatabase(dbName)
  283. if err != nil {
  284. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  285. return
  286. }
  287. // Extract table name from path
  288. path := strings.TrimPrefix(r.URL.Path, "/schema/tables/")
  289. tableName := strings.TrimSpace(path)
  290. if tableName == "" {
  291. writeError(w, http.StatusBadRequest, "MISSING_TABLE_NAME", "Table name is required", nil)
  292. return
  293. }
  294. schema, err := schemaManager.GetSchema(tableName)
  295. if err != nil {
  296. writeError(w, http.StatusNotFound, "TABLE_NOT_FOUND", fmt.Sprintf("Table '%s' not found", tableName), nil)
  297. return
  298. }
  299. columns := make([]map[string]interface{}, len(schema.Columns))
  300. for i, col := range schema.Columns {
  301. columns[i] = map[string]interface{}{
  302. "name": col.Name,
  303. "type": col.Type,
  304. "nullable": col.Nullable,
  305. "primaryKey": col.PrimaryKey,
  306. "default": col.Default,
  307. }
  308. }
  309. resp := map[string]interface{}{
  310. "name": schema.Name,
  311. "columns": columns,
  312. }
  313. pretty := r.URL.Query().Get("pretty") == "true"
  314. writeJSON(w, http.StatusOK, resp, pretty)
  315. }
  316. // handleHealth handles GET /health
  317. func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
  318. resp := map[string]interface{}{
  319. "status": "ok",
  320. "version": "0.1.0",
  321. "uptime": time.Since(s.stats.StartTime).String(),
  322. }
  323. pretty := r.URL.Query().Get("pretty") == "true"
  324. writeJSON(w, http.StatusOK, resp, pretty)
  325. }
  326. // handleStats handles GET /stats
  327. func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) {
  328. // Get database from X-Database header
  329. dbName := r.Header.Get("X-Database")
  330. _, schema, _ := s.getExecutorForDatabase(dbName)
  331. var tables []string
  332. if schema != nil {
  333. tables, _ = schema.ListTables()
  334. }
  335. var avgQueryTime string
  336. if s.stats.QueriesExecuted > 0 {
  337. avgQueryTime = "N/A" // TODO: Track actual query times
  338. } else {
  339. avgQueryTime = "0ms"
  340. }
  341. resp := map[string]interface{}{
  342. "queriesExecuted": atomic.LoadInt64(&s.stats.QueriesExecuted),
  343. "queriesSuccess": atomic.LoadInt64(&s.stats.QueriesSuccess),
  344. "queriesError": atomic.LoadInt64(&s.stats.QueriesError),
  345. "tablesCount": len(tables),
  346. "avgQueryTime": avgQueryTime,
  347. "uptime": time.Since(s.stats.StartTime).String(),
  348. }
  349. pretty := r.URL.Query().Get("pretty") == "true"
  350. writeJSON(w, http.StatusOK, resp, pretty)
  351. }
  352. // handleTransactionBegin handles POST /transaction/begin
  353. func (s *Server) handleTransactionBegin(w http.ResponseWriter, r *http.Request) {
  354. if r.Method != http.MethodPost {
  355. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  356. return
  357. }
  358. // Get database from X-Database header
  359. dbName := r.Header.Get("X-Database")
  360. exec, _, err := s.getExecutorForDatabase(dbName)
  361. if err != nil {
  362. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  363. return
  364. }
  365. l := lexer.New("BEGIN")
  366. p := parser.New(l)
  367. stmt, _ := p.Parse()
  368. _, err = exec.Execute(stmt)
  369. if err != nil {
  370. writeError(w, http.StatusInternalServerError, "TRANSACTION_ERROR", err.Error(), nil)
  371. return
  372. }
  373. // Generate transaction ID (simple implementation)
  374. txID := fmt.Sprintf("tx-%d", time.Now().UnixNano())
  375. resp := map[string]interface{}{
  376. "transactionId": txID,
  377. }
  378. pretty := r.URL.Query().Get("pretty") == "true"
  379. writeJSON(w, http.StatusOK, resp, pretty)
  380. }
  381. // handleTransactionCommit handles POST /transaction/commit
  382. func (s *Server) handleTransactionCommit(w http.ResponseWriter, r *http.Request) {
  383. if r.Method != http.MethodPost {
  384. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  385. return
  386. }
  387. // Get database from X-Database header
  388. dbName := r.Header.Get("X-Database")
  389. exec, _, err := s.getExecutorForDatabase(dbName)
  390. if err != nil {
  391. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  392. return
  393. }
  394. var req TransactionRequest
  395. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  396. // Allow commit without transaction ID for simplicity
  397. }
  398. l := lexer.New("COMMIT")
  399. p := parser.New(l)
  400. stmt, _ := p.Parse()
  401. _, err = exec.Execute(stmt)
  402. if err != nil {
  403. writeError(w, http.StatusInternalServerError, "TRANSACTION_ERROR", err.Error(), nil)
  404. return
  405. }
  406. resp := map[string]interface{}{
  407. "status": "committed",
  408. }
  409. pretty := r.URL.Query().Get("pretty") == "true"
  410. writeJSON(w, http.StatusOK, resp, pretty)
  411. }
  412. // substituteParams replaces ? placeholders with actual parameter values.
  413. // This is a simple implementation that handles basic SQL escaping.
  414. func substituteParams(sql string, params []interface{}) string {
  415. if len(params) == 0 {
  416. return sql
  417. }
  418. result := sql
  419. for _, param := range params {
  420. idx := strings.Index(result, "?")
  421. if idx == -1 {
  422. break
  423. }
  424. var replacement string
  425. switch v := param.(type) {
  426. case nil:
  427. replacement = "NULL"
  428. case string:
  429. // Escape single quotes in strings
  430. escaped := strings.ReplaceAll(v, "'", "''")
  431. replacement = "'" + escaped + "'"
  432. case int, int64, int32, int16, int8:
  433. replacement = fmt.Sprintf("%d", v)
  434. case float64, float32:
  435. replacement = fmt.Sprintf("%g", v)
  436. case bool:
  437. if v {
  438. replacement = "1"
  439. } else {
  440. replacement = "0"
  441. }
  442. default:
  443. // For other types, convert to string
  444. escaped := strings.ReplaceAll(fmt.Sprintf("%v", v), "'", "''")
  445. replacement = "'" + escaped + "'"
  446. }
  447. result = result[:idx] + replacement + result[idx+1:]
  448. }
  449. return result
  450. }
  451. // inferType infers SQL type from a Go value.
  452. func inferType(v interface{}) string {
  453. switch v.(type) {
  454. case nil:
  455. return "NULL"
  456. case int, int64, int32, int16, int8:
  457. return "INTEGER"
  458. case float64, float32:
  459. return "REAL"
  460. case string:
  461. return "TEXT"
  462. case []byte:
  463. return "BLOB"
  464. case bool:
  465. return "INTEGER"
  466. default:
  467. return "ANY"
  468. }
  469. }
  470. // handleTransactionRollback handles POST /transaction/rollback
  471. func (s *Server) handleTransactionRollback(w http.ResponseWriter, r *http.Request) {
  472. if r.Method != http.MethodPost {
  473. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  474. return
  475. }
  476. // Get database from X-Database header
  477. dbName := r.Header.Get("X-Database")
  478. exec, _, err := s.getExecutorForDatabase(dbName)
  479. if err != nil {
  480. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  481. return
  482. }
  483. var req TransactionRequest
  484. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  485. // Allow rollback without transaction ID for simplicity
  486. }
  487. l := lexer.New("ROLLBACK")
  488. p := parser.New(l)
  489. stmt, _ := p.Parse()
  490. _, err = exec.Execute(stmt)
  491. if err != nil {
  492. writeError(w, http.StatusInternalServerError, "TRANSACTION_ERROR", err.Error(), nil)
  493. return
  494. }
  495. resp := map[string]interface{}{
  496. "status": "rolled back",
  497. }
  498. pretty := r.URL.Query().Get("pretty") == "true"
  499. writeJSON(w, http.StatusOK, resp, pretty)
  500. }
  501. // handleMetrics handles GET /metrics in Prometheus format
  502. func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request) {
  503. if r.Method != http.MethodGet {
  504. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only GET method is allowed", nil)
  505. return
  506. }
  507. // Get database from X-Database header
  508. dbName := r.Header.Get("X-Database")
  509. _, schema, _ := s.getExecutorForDatabase(dbName)
  510. var tables []string
  511. if schema != nil {
  512. tables, _ = schema.ListTables()
  513. }
  514. uptime := time.Since(s.stats.StartTime).Seconds()
  515. queriesTotal := atomic.LoadInt64(&s.stats.QueriesExecuted)
  516. queriesSuccess := atomic.LoadInt64(&s.stats.QueriesSuccess)
  517. queriesError := atomic.LoadInt64(&s.stats.QueriesError)
  518. w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
  519. // Write Prometheus format metrics
  520. fmt.Fprintf(w, "# HELP pizzasql_queries_total Total number of queries executed\n")
  521. fmt.Fprintf(w, "# TYPE pizzasql_queries_total counter\n")
  522. fmt.Fprintf(w, "pizzasql_queries_total{status=\"success\"} %d\n", queriesSuccess)
  523. fmt.Fprintf(w, "pizzasql_queries_total{status=\"error\"} %d\n", queriesError)
  524. fmt.Fprintf(w, "\n")
  525. fmt.Fprintf(w, "# HELP pizzasql_queries_executed_total Total queries executed (all statuses)\n")
  526. fmt.Fprintf(w, "# TYPE pizzasql_queries_executed_total counter\n")
  527. fmt.Fprintf(w, "pizzasql_queries_executed_total %d\n", queriesTotal)
  528. fmt.Fprintf(w, "\n")
  529. fmt.Fprintf(w, "# HELP pizzasql_tables_count Number of tables in the database\n")
  530. fmt.Fprintf(w, "# TYPE pizzasql_tables_count gauge\n")
  531. fmt.Fprintf(w, "pizzasql_tables_count %d\n", len(tables))
  532. fmt.Fprintf(w, "\n")
  533. fmt.Fprintf(w, "# HELP pizzasql_uptime_seconds Server uptime in seconds\n")
  534. fmt.Fprintf(w, "# TYPE pizzasql_uptime_seconds gauge\n")
  535. fmt.Fprintf(w, "pizzasql_uptime_seconds %.2f\n", uptime)
  536. fmt.Fprintf(w, "\n")
  537. fmt.Fprintf(w, "# HELP pizzasql_info PizzaSQL server information\n")
  538. fmt.Fprintf(w, "# TYPE pizzasql_info gauge\n")
  539. fmt.Fprintf(w, "pizzasql_info{version=\"0.1.0\"} 1\n")
  540. }
  541. // handleExport handles GET /export
  542. func (s *Server) handleExport(w http.ResponseWriter, r *http.Request) {
  543. if r.Method != http.MethodGet {
  544. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only GET method is allowed", nil)
  545. return
  546. }
  547. // Get database from X-Database header
  548. dbName := strings.TrimSpace(r.Header.Get("X-Database"))
  549. _, schema, err := s.getExecutorForDatabase(dbName)
  550. if err != nil {
  551. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  552. return
  553. }
  554. // Get the table manager from the database instance
  555. dbInstance, err := s.dbManager.GetDatabase(dbName)
  556. if err != nil {
  557. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  558. return
  559. }
  560. // Get format parameter (default: sql)
  561. format := strings.ToLower(r.URL.Query().Get("format"))
  562. if format == "" {
  563. format = "sql"
  564. }
  565. tableName := r.URL.Query().Get("table")
  566. switch format {
  567. case "csv":
  568. // CSV export requires a single table
  569. if tableName == "" {
  570. writeError(w, http.StatusBadRequest, "TABLE_REQUIRED", "CSV export requires 'table' parameter", nil)
  571. return
  572. }
  573. csvOpts := csvexport.DefaultExportOptions()
  574. csvOpts.Table = tableName
  575. data, err := csvexport.ExportTableToBytes(schema, dbInstance.Table, csvOpts)
  576. if err != nil {
  577. writeError(w, http.StatusInternalServerError, "EXPORT_ERROR", err.Error(), nil)
  578. return
  579. }
  580. w.Header().Set("Content-Type", "text/csv")
  581. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s.csv\"", tableName))
  582. w.WriteHeader(http.StatusOK)
  583. w.Write(data)
  584. case "sql", "sqlite":
  585. // SQL export (also used for SQLite-compatible export)
  586. opts := sqlexport.DefaultExportOptions()
  587. // Specific table(s) to export
  588. if tableName != "" {
  589. opts.Tables = strings.Split(tableName, ",")
  590. }
  591. // Include data (default: true)
  592. if r.URL.Query().Get("schema_only") == "true" {
  593. opts.IncludeData = false
  594. }
  595. // Include DROP TABLE statements
  596. if r.URL.Query().Get("drop") == "true" {
  597. opts.DropTables = true
  598. }
  599. // Generate SQL export
  600. sql, err := sqlexport.ExportDatabase(schema, dbInstance.Table, opts)
  601. if err != nil {
  602. writeError(w, http.StatusInternalServerError, "EXPORT_ERROR", err.Error(), nil)
  603. return
  604. }
  605. // Determine filename and content type
  606. ext := "sql"
  607. contentType := "application/sql"
  608. if format == "sqlite" {
  609. ext = "sql" // Still SQL text, but sqlite-compatible
  610. }
  611. filename := schema.GetDatabaseName() + "_export." + ext
  612. if len(opts.Tables) == 1 {
  613. filename = opts.Tables[0] + "_export." + ext
  614. }
  615. w.Header().Set("Content-Type", contentType)
  616. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
  617. w.WriteHeader(http.StatusOK)
  618. w.Write([]byte(sql))
  619. default:
  620. writeError(w, http.StatusBadRequest, "INVALID_FORMAT",
  621. fmt.Sprintf("Invalid format '%s'. Supported formats: sql, csv", format), nil)
  622. }
  623. }
  624. // handleImport handles POST /import
  625. func (s *Server) handleImport(w http.ResponseWriter, r *http.Request) {
  626. if r.Method != http.MethodPost {
  627. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  628. return
  629. }
  630. // Get database from X-Database header
  631. dbName := strings.TrimSpace(r.Header.Get("X-Database"))
  632. exec, schema, err := s.getExecutorForDatabase(dbName)
  633. if err != nil {
  634. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  635. return
  636. }
  637. // Get the table manager from the database instance
  638. dbInstance, err := s.dbManager.GetDatabase(dbName)
  639. if err != nil {
  640. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  641. return
  642. }
  643. // Get format parameter (default: sql, can be auto-detected)
  644. format := strings.ToLower(r.URL.Query().Get("format"))
  645. tableName := r.URL.Query().Get("table")
  646. ignoreErrors := r.URL.Query().Get("ignore_errors") == "true"
  647. createTable := r.URL.Query().Get("create_table") == "true"
  648. pretty := r.URL.Query().Get("pretty") == "true"
  649. // Check content type
  650. contentType := r.Header.Get("Content-Type")
  651. var fileContent []byte
  652. var filename string
  653. if strings.HasPrefix(contentType, "multipart/form-data") {
  654. // Handle file upload
  655. if err := r.ParseMultipartForm(32 << 20); err != nil { // 32MB max
  656. writeError(w, http.StatusBadRequest, "INVALID_FORM", "Failed to parse multipart form: "+err.Error(), nil)
  657. return
  658. }
  659. file, header, err := r.FormFile("file")
  660. if err != nil {
  661. writeError(w, http.StatusBadRequest, "MISSING_FILE", "No file uploaded. Use 'file' field name.", nil)
  662. return
  663. }
  664. defer file.Close()
  665. filename = header.Filename
  666. // Read file content
  667. fileContent, err = io.ReadAll(file)
  668. if err != nil {
  669. writeError(w, http.StatusBadRequest, "READ_ERROR", "Failed to read uploaded file: "+err.Error(), nil)
  670. return
  671. }
  672. } else if strings.HasPrefix(contentType, "application/json") {
  673. // Handle JSON body with SQL content
  674. var req struct {
  675. SQL string `json:"sql"`
  676. }
  677. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  678. writeError(w, http.StatusBadRequest, "INVALID_JSON", "Invalid JSON in request body", nil)
  679. return
  680. }
  681. fileContent = []byte(req.SQL)
  682. } else if strings.HasPrefix(contentType, "text/plain") || strings.HasPrefix(contentType, "application/sql") || strings.HasPrefix(contentType, "text/csv") {
  683. // Handle raw content in body
  684. var err error
  685. fileContent, err = io.ReadAll(r.Body)
  686. if err != nil {
  687. writeError(w, http.StatusBadRequest, "READ_ERROR", "Failed to read request body: "+err.Error(), nil)
  688. return
  689. }
  690. // Auto-detect CSV from content type
  691. if strings.HasPrefix(contentType, "text/csv") && format == "" {
  692. format = "csv"
  693. }
  694. } else {
  695. writeError(w, http.StatusBadRequest, "INVALID_CONTENT_TYPE",
  696. "Content-Type must be multipart/form-data, application/json, text/plain, text/csv, or application/sql", nil)
  697. return
  698. }
  699. if len(fileContent) == 0 {
  700. writeError(w, http.StatusBadRequest, "EMPTY_CONTENT", "No content provided", nil)
  701. return
  702. }
  703. // Auto-detect format from filename extension if not specified
  704. if format == "" && filename != "" {
  705. if strings.HasSuffix(strings.ToLower(filename), ".csv") {
  706. format = "csv"
  707. }
  708. }
  709. if format == "" {
  710. format = "sql"
  711. }
  712. switch format {
  713. case "csv":
  714. // CSV import requires table name
  715. if tableName == "" {
  716. writeError(w, http.StatusBadRequest, "TABLE_REQUIRED", "CSV import requires 'table' parameter", nil)
  717. return
  718. }
  719. csvOpts := csvimport.DefaultImportOptions()
  720. csvOpts.TableName = tableName
  721. csvOpts.IgnoreErrors = ignoreErrors
  722. csvOpts.CreateTable = createTable
  723. result, err := csvimport.ImportCSV(strings.NewReader(string(fileContent)), schema, dbInstance.Table, csvOpts)
  724. if err != nil && !ignoreErrors {
  725. writeError(w, http.StatusBadRequest, "IMPORT_ERROR", err.Error(), map[string]interface{}{
  726. "rowsImported": result.RowsImported,
  727. "rowsSkipped": result.RowsSkipped,
  728. "tableCreated": result.TableCreated,
  729. "errors": result.Errors,
  730. })
  731. return
  732. }
  733. // Sync catalog after import
  734. exec.SyncCatalog()
  735. writeJSON(w, http.StatusOK, result, pretty)
  736. case "sql", "sqlite":
  737. // SQL import
  738. opts := sqlimport.DefaultImportOptions()
  739. opts.IgnoreErrors = ignoreErrors
  740. result, err := sqlimport.ImportSQL(exec, string(fileContent), opts)
  741. if err != nil && !ignoreErrors {
  742. writeError(w, http.StatusBadRequest, "IMPORT_ERROR", err.Error(), map[string]interface{}{
  743. "statementsExecuted": result.StatementsExecuted,
  744. "tablesCreated": result.TablesCreated,
  745. "rowsInserted": result.RowsInserted,
  746. "errors": result.Errors,
  747. })
  748. return
  749. }
  750. // Sync catalog after import
  751. exec.SyncCatalog()
  752. writeJSON(w, http.StatusOK, result, pretty)
  753. default:
  754. writeError(w, http.StatusBadRequest, "INVALID_FORMAT",
  755. fmt.Sprintf("Invalid format '%s'. Supported formats: sql, csv", format), nil)
  756. }
  757. }