handler.go 28 KB

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