2
0

handler.go 29 KB

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