handler.go 30 KB

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