2
0

handler.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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.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. // 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 strings.HasPrefix(message, "CHECK constraint failed: ") {
  392. constraint := strings.TrimPrefix(message, "CHECK constraint failed: ")
  393. return &HTTPError{
  394. Status: http.StatusBadRequest,
  395. Code: "23514",
  396. Message: message,
  397. Details: map[string]interface{}{"constraint": constraint},
  398. }
  399. }
  400. if errors.Is(err, storage.ErrSerialization) {
  401. return &HTTPError{
  402. Status: http.StatusConflict,
  403. Code: "40001",
  404. Message: message,
  405. }
  406. }
  407. if strings.Contains(message, "feature not supported:") {
  408. return &HTTPError{
  409. Status: http.StatusBadRequest,
  410. Code: "0A000",
  411. Message: message,
  412. }
  413. }
  414. return &HTTPError{
  415. Status: http.StatusInternalServerError,
  416. Code: "EXECUTION_ERROR",
  417. Message: message,
  418. }
  419. }
  420. // handleHealth handles GET /health
  421. func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
  422. resp := map[string]interface{}{
  423. "status": "ok",
  424. "version": version.String(),
  425. "uptime": time.Since(s.stats.StartTime).String(),
  426. }
  427. pretty := r.URL.Query().Get("pretty") == "true"
  428. writeJSON(w, http.StatusOK, resp, pretty)
  429. }
  430. // handleStats handles GET /stats
  431. func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) {
  432. // Get database from X-Database header
  433. dbName := r.Header.Get("X-Database")
  434. _, schema, _ := s.getExecutorForDatabase(dbName)
  435. var tables []string
  436. if schema != nil {
  437. tables, _ = schema.ListTables()
  438. }
  439. var avgQueryTime string
  440. if s.stats.QueriesExecuted > 0 {
  441. avgQueryTime = "N/A" // TODO: Track actual query times
  442. } else {
  443. avgQueryTime = "0ms"
  444. }
  445. resp := map[string]interface{}{
  446. "queriesExecuted": atomic.LoadInt64(&s.stats.QueriesExecuted),
  447. "queriesSuccess": atomic.LoadInt64(&s.stats.QueriesSuccess),
  448. "queriesError": atomic.LoadInt64(&s.stats.QueriesError),
  449. "tablesCount": len(tables),
  450. "avgQueryTime": avgQueryTime,
  451. "uptime": time.Since(s.stats.StartTime).String(),
  452. }
  453. pretty := r.URL.Query().Get("pretty") == "true"
  454. writeJSON(w, http.StatusOK, resp, pretty)
  455. }
  456. // handleTransactionBegin handles POST /transaction/begin
  457. func (s *Server) handleTransactionBegin(w http.ResponseWriter, r *http.Request) {
  458. if r.Method != http.MethodPost {
  459. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  460. return
  461. }
  462. // Get database from X-Database header
  463. dbName := r.Header.Get("X-Database")
  464. txID, _, err := s.beginTransaction(dbName)
  465. if err != nil {
  466. writeError(w, http.StatusInternalServerError, "TRANSACTION_ERROR", err.Error(), nil)
  467. return
  468. }
  469. resp := map[string]interface{}{
  470. "transactionId": txID,
  471. "status": "started",
  472. }
  473. pretty := r.URL.Query().Get("pretty") == "true"
  474. writeJSON(w, http.StatusOK, resp, pretty)
  475. }
  476. // handleTransactionCommit handles POST /transaction/commit
  477. func (s *Server) handleTransactionCommit(w http.ResponseWriter, r *http.Request) {
  478. if r.Method != http.MethodPost {
  479. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  480. return
  481. }
  482. var req TransactionRequest
  483. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  484. writeError(w, http.StatusBadRequest, "INVALID_JSON", "Invalid JSON in request body", nil)
  485. return
  486. }
  487. tx, ok := s.takeTransactionExecutor(req.TransactionID, r.Header.Get("X-Database"))
  488. if !ok {
  489. writeError(w, http.StatusNotFound, "TRANSACTION_NOT_FOUND", "unknown transaction ID", nil)
  490. return
  491. }
  492. defer tx.mu.Unlock()
  493. l := lexer.New("COMMIT")
  494. p := parser.New(l)
  495. stmt, _ := p.Parse()
  496. if _, err := tx.exec.Execute(stmt); err != nil {
  497. if errors.Is(err, storage.ErrSerialization) {
  498. writeError(w, http.StatusConflict, "SERIALIZATION_FAILURE", err.Error(), nil)
  499. } else {
  500. writeError(w, http.StatusBadRequest, "TRANSACTION_ERROR", err.Error(), nil)
  501. }
  502. return
  503. }
  504. resp := map[string]interface{}{
  505. "status": "committed",
  506. }
  507. pretty := r.URL.Query().Get("pretty") == "true"
  508. writeJSON(w, http.StatusOK, resp, pretty)
  509. }
  510. // substituteParams replaces ? placeholders with actual parameter values.
  511. // This is a simple implementation that handles basic SQL escaping.
  512. func substituteParams(sql string, params []interface{}) string {
  513. if len(params) == 0 {
  514. return sql
  515. }
  516. result := sql
  517. for _, param := range params {
  518. idx := strings.Index(result, "?")
  519. if idx == -1 {
  520. break
  521. }
  522. var replacement string
  523. switch v := param.(type) {
  524. case nil:
  525. replacement = "NULL"
  526. case string:
  527. // Escape single quotes in strings
  528. escaped := strings.ReplaceAll(v, "'", "''")
  529. replacement = "'" + escaped + "'"
  530. case int, int64, int32, int16, int8:
  531. replacement = fmt.Sprintf("%d", v)
  532. case float64, float32:
  533. replacement = fmt.Sprintf("%g", v)
  534. case bool:
  535. if v {
  536. replacement = "1"
  537. } else {
  538. replacement = "0"
  539. }
  540. default:
  541. // For other types, convert to string
  542. escaped := strings.ReplaceAll(fmt.Sprintf("%v", v), "'", "''")
  543. replacement = "'" + escaped + "'"
  544. }
  545. result = result[:idx] + replacement + result[idx+1:]
  546. }
  547. return result
  548. }
  549. // inferType infers SQL type from a Go value.
  550. func inferType(v interface{}) string {
  551. switch v.(type) {
  552. case nil:
  553. return "NULL"
  554. case int, int64, int32, int16, int8:
  555. return "INTEGER"
  556. case float64, float32:
  557. return "REAL"
  558. case string:
  559. return "TEXT"
  560. case []byte:
  561. return "BLOB"
  562. case bool:
  563. return "INTEGER"
  564. default:
  565. return "ANY"
  566. }
  567. }
  568. // handleTransactionRollback handles POST /transaction/rollback
  569. func (s *Server) handleTransactionRollback(w http.ResponseWriter, r *http.Request) {
  570. if r.Method != http.MethodPost {
  571. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  572. return
  573. }
  574. var req TransactionRequest
  575. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  576. writeError(w, http.StatusBadRequest, "INVALID_JSON", "Invalid JSON in request body", nil)
  577. return
  578. }
  579. tx, ok := s.takeTransactionExecutor(req.TransactionID, r.Header.Get("X-Database"))
  580. if !ok {
  581. writeError(w, http.StatusNotFound, "TRANSACTION_NOT_FOUND", "unknown transaction ID", nil)
  582. return
  583. }
  584. defer tx.mu.Unlock()
  585. l := lexer.New("ROLLBACK")
  586. p := parser.New(l)
  587. stmt, _ := p.Parse()
  588. if _, err := tx.exec.Execute(stmt); err != nil {
  589. writeError(w, http.StatusBadRequest, "TRANSACTION_ERROR", err.Error(), nil)
  590. return
  591. }
  592. resp := map[string]interface{}{
  593. "status": "rolled back",
  594. }
  595. pretty := r.URL.Query().Get("pretty") == "true"
  596. writeJSON(w, http.StatusOK, resp, pretty)
  597. }
  598. // handleMetrics handles GET /metrics in Prometheus format
  599. func (s *Server) handleMetrics(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 := r.Header.Get("X-Database")
  606. _, schema, _ := s.getExecutorForDatabase(dbName)
  607. var tables []string
  608. if schema != nil {
  609. tables, _ = schema.ListTables()
  610. }
  611. uptime := time.Since(s.stats.StartTime).Seconds()
  612. queriesTotal := atomic.LoadInt64(&s.stats.QueriesExecuted)
  613. queriesSuccess := atomic.LoadInt64(&s.stats.QueriesSuccess)
  614. queriesError := atomic.LoadInt64(&s.stats.QueriesError)
  615. w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
  616. // Write Prometheus format metrics
  617. fmt.Fprintf(w, "# HELP pizzasql_queries_total Total number of queries executed\n")
  618. fmt.Fprintf(w, "# TYPE pizzasql_queries_total counter\n")
  619. fmt.Fprintf(w, "pizzasql_queries_total{status=\"success\"} %d\n", queriesSuccess)
  620. fmt.Fprintf(w, "pizzasql_queries_total{status=\"error\"} %d\n", queriesError)
  621. fmt.Fprintf(w, "\n")
  622. fmt.Fprintf(w, "# HELP pizzasql_queries_executed_total Total queries executed (all statuses)\n")
  623. fmt.Fprintf(w, "# TYPE pizzasql_queries_executed_total counter\n")
  624. fmt.Fprintf(w, "pizzasql_queries_executed_total %d\n", queriesTotal)
  625. fmt.Fprintf(w, "\n")
  626. fmt.Fprintf(w, "# HELP pizzasql_tables_count Number of tables in the database\n")
  627. fmt.Fprintf(w, "# TYPE pizzasql_tables_count gauge\n")
  628. fmt.Fprintf(w, "pizzasql_tables_count %d\n", len(tables))
  629. fmt.Fprintf(w, "\n")
  630. fmt.Fprintf(w, "# HELP pizzasql_uptime_seconds Server uptime in seconds\n")
  631. fmt.Fprintf(w, "# TYPE pizzasql_uptime_seconds gauge\n")
  632. fmt.Fprintf(w, "pizzasql_uptime_seconds %.2f\n", uptime)
  633. fmt.Fprintf(w, "\n")
  634. fmt.Fprintf(w, "# HELP pizzasql_info PizzaSQL server information\n")
  635. fmt.Fprintf(w, "# TYPE pizzasql_info gauge\n")
  636. fmt.Fprintf(w, "pizzasql_info{version=\"%s\"} 1\n", version.PrometheusLabel())
  637. }
  638. // handleExport handles GET /export
  639. func (s *Server) handleExport(w http.ResponseWriter, r *http.Request) {
  640. if r.Method != http.MethodGet {
  641. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only GET method is allowed", nil)
  642. return
  643. }
  644. // Get database from X-Database header
  645. dbName := strings.TrimSpace(r.Header.Get("X-Database"))
  646. _, schema, err := s.getExecutorForDatabase(dbName)
  647. if err != nil {
  648. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  649. return
  650. }
  651. // Get the table manager from the database instance
  652. dbInstance, err := s.dbManager.GetDatabase(dbName)
  653. if err != nil {
  654. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  655. return
  656. }
  657. // Get format parameter (default: sql)
  658. format := strings.ToLower(r.URL.Query().Get("format"))
  659. if format == "" {
  660. format = "sql"
  661. }
  662. tableName := r.URL.Query().Get("table")
  663. switch format {
  664. case "csv":
  665. // CSV export requires a single table
  666. if tableName == "" {
  667. writeError(w, http.StatusBadRequest, "TABLE_REQUIRED", "CSV export requires 'table' parameter", nil)
  668. return
  669. }
  670. csvOpts := csvexport.DefaultExportOptions()
  671. csvOpts.Table = tableName
  672. data, err := csvexport.ExportTableToBytes(schema, dbInstance.Table, csvOpts)
  673. if err != nil {
  674. writeError(w, http.StatusInternalServerError, "EXPORT_ERROR", err.Error(), nil)
  675. return
  676. }
  677. w.Header().Set("Content-Type", "text/csv")
  678. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s.csv\"", tableName))
  679. w.WriteHeader(http.StatusOK)
  680. w.Write(data)
  681. case "sql", "sqlite":
  682. // SQL export (also used for SQLite-compatible export)
  683. opts := sqlexport.DefaultExportOptions()
  684. // Specific table(s) to export
  685. if tableName != "" {
  686. opts.Tables = strings.Split(tableName, ",")
  687. }
  688. // Include data (default: true)
  689. if r.URL.Query().Get("schema_only") == "true" {
  690. opts.IncludeData = false
  691. }
  692. // Include DROP TABLE statements
  693. if r.URL.Query().Get("drop") == "true" {
  694. opts.DropTables = true
  695. }
  696. // Generate SQL export
  697. sql, err := sqlexport.ExportDatabase(schema, dbInstance.Table, opts)
  698. if err != nil {
  699. writeError(w, http.StatusInternalServerError, "EXPORT_ERROR", err.Error(), nil)
  700. return
  701. }
  702. // Determine filename and content type
  703. ext := "sql"
  704. contentType := "application/sql"
  705. if format == "sqlite" {
  706. ext = "sql" // Still SQL text, but sqlite-compatible
  707. }
  708. filename := schema.GetDatabaseName() + "_export." + ext
  709. if len(opts.Tables) == 1 {
  710. filename = opts.Tables[0] + "_export." + ext
  711. }
  712. w.Header().Set("Content-Type", contentType)
  713. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
  714. w.WriteHeader(http.StatusOK)
  715. w.Write([]byte(sql))
  716. default:
  717. writeError(w, http.StatusBadRequest, "INVALID_FORMAT",
  718. fmt.Sprintf("Invalid format '%s'. Supported formats: sql, csv", format), nil)
  719. }
  720. }
  721. // handleImport handles POST /import
  722. func (s *Server) handleImport(w http.ResponseWriter, r *http.Request) {
  723. if r.Method != http.MethodPost {
  724. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  725. return
  726. }
  727. // Get database from X-Database header
  728. dbName := strings.TrimSpace(r.Header.Get("X-Database"))
  729. exec, schema, err := s.getExecutorForDatabase(dbName)
  730. if err != nil {
  731. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  732. return
  733. }
  734. // Get the table manager from the database instance
  735. dbInstance, err := s.dbManager.GetDatabase(dbName)
  736. if err != nil {
  737. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  738. return
  739. }
  740. // Get format parameter (default: sql, can be auto-detected)
  741. format := strings.ToLower(r.URL.Query().Get("format"))
  742. tableName := r.URL.Query().Get("table")
  743. ignoreErrors := r.URL.Query().Get("ignore_errors") == "true"
  744. createTable := r.URL.Query().Get("create_table") == "true"
  745. pretty := r.URL.Query().Get("pretty") == "true"
  746. // Check content type
  747. contentType := r.Header.Get("Content-Type")
  748. var fileContent []byte
  749. var filename string
  750. if strings.HasPrefix(contentType, "multipart/form-data") {
  751. // Handle file upload
  752. if err := r.ParseMultipartForm(32 << 20); err != nil { // 32MB max
  753. writeError(w, http.StatusBadRequest, "INVALID_FORM", "Failed to parse multipart form: "+err.Error(), nil)
  754. return
  755. }
  756. file, header, err := r.FormFile("file")
  757. if err != nil {
  758. writeError(w, http.StatusBadRequest, "MISSING_FILE", "No file uploaded. Use 'file' field name.", nil)
  759. return
  760. }
  761. defer file.Close()
  762. filename = header.Filename
  763. // Read file content
  764. fileContent, err = io.ReadAll(file)
  765. if err != nil {
  766. writeError(w, http.StatusBadRequest, "READ_ERROR", "Failed to read uploaded file: "+err.Error(), nil)
  767. return
  768. }
  769. } else if strings.HasPrefix(contentType, "application/json") {
  770. // Handle JSON body with SQL content
  771. var req struct {
  772. SQL string `json:"sql"`
  773. }
  774. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  775. writeError(w, http.StatusBadRequest, "INVALID_JSON", "Invalid JSON in request body", nil)
  776. return
  777. }
  778. fileContent = []byte(req.SQL)
  779. } else if strings.HasPrefix(contentType, "text/plain") || strings.HasPrefix(contentType, "application/sql") || strings.HasPrefix(contentType, "text/csv") {
  780. // Handle raw content in body
  781. var err error
  782. fileContent, err = io.ReadAll(r.Body)
  783. if err != nil {
  784. writeError(w, http.StatusBadRequest, "READ_ERROR", "Failed to read request body: "+err.Error(), nil)
  785. return
  786. }
  787. // Auto-detect CSV from content type
  788. if strings.HasPrefix(contentType, "text/csv") && format == "" {
  789. format = "csv"
  790. }
  791. } else {
  792. writeError(w, http.StatusBadRequest, "INVALID_CONTENT_TYPE",
  793. "Content-Type must be multipart/form-data, application/json, text/plain, text/csv, or application/sql", nil)
  794. return
  795. }
  796. if len(fileContent) == 0 {
  797. writeError(w, http.StatusBadRequest, "EMPTY_CONTENT", "No content provided", nil)
  798. return
  799. }
  800. // Auto-detect format from filename extension if not specified
  801. if format == "" && filename != "" {
  802. lower := strings.ToLower(filename)
  803. if strings.HasSuffix(lower, ".csv") {
  804. format = "csv"
  805. } else if strings.HasSuffix(lower, ".db") || strings.HasSuffix(lower, ".sqlite") || strings.HasSuffix(lower, ".sqlite3") {
  806. format = "sqlite"
  807. }
  808. }
  809. // Detect binary SQLite from content-type
  810. if format == "" {
  811. ct := strings.ToLower(contentType)
  812. if strings.Contains(ct, "application/x-sqlite3") || strings.Contains(ct, "application/octet-stream") {
  813. format = "sqlite"
  814. }
  815. }
  816. // Check magic bytes: SQLite files start with "SQLite format 3\000"
  817. if format == "" && len(fileContent) >= 16 && string(fileContent[:15]) == "SQLite format 3" {
  818. format = "sqlite"
  819. }
  820. if format == "" {
  821. format = "sql"
  822. }
  823. switch format {
  824. case "csv":
  825. // CSV import requires table name
  826. if tableName == "" {
  827. writeError(w, http.StatusBadRequest, "TABLE_REQUIRED", "CSV import requires 'table' parameter", nil)
  828. return
  829. }
  830. csvOpts := csvimport.DefaultImportOptions()
  831. csvOpts.TableName = tableName
  832. csvOpts.IgnoreErrors = ignoreErrors
  833. csvOpts.CreateTable = createTable
  834. result, err := csvimport.ImportCSV(strings.NewReader(string(fileContent)), schema, dbInstance.Table, csvOpts)
  835. if err != nil && !ignoreErrors {
  836. writeError(w, http.StatusBadRequest, "IMPORT_ERROR", err.Error(), map[string]interface{}{
  837. "rowsImported": result.RowsImported,
  838. "rowsSkipped": result.RowsSkipped,
  839. "tableCreated": result.TableCreated,
  840. "errors": result.Errors,
  841. })
  842. return
  843. }
  844. // Sync catalog after import
  845. exec.SyncCatalog()
  846. writeJSON(w, http.StatusOK, result, pretty)
  847. case "sqlite":
  848. // Binary SQLite .db import
  849. opts := sqliteimport.DefaultImportOptions()
  850. opts.CreateTables = r.URL.Query().Get("create_tables") != "false"
  851. opts.IgnoreErrors = ignoreErrors
  852. result, err := sqliteimport.ImportSQLiteBytes(fileContent, exec, opts)
  853. if err != nil && !ignoreErrors {
  854. writeError(w, http.StatusBadRequest, "IMPORT_ERROR", err.Error(), map[string]interface{}{
  855. "tablesCreated": result.TablesCreated,
  856. "rowsInserted": result.RowsInserted,
  857. "errors": result.Errors,
  858. })
  859. return
  860. }
  861. exec.SyncCatalog()
  862. writeJSON(w, http.StatusOK, result, pretty)
  863. case "sql":
  864. // SQL text import
  865. opts := sqlimport.DefaultImportOptions()
  866. opts.IgnoreErrors = ignoreErrors
  867. result, err := sqlimport.ImportSQL(exec, string(fileContent), opts)
  868. if err != nil && !ignoreErrors {
  869. writeError(w, http.StatusBadRequest, "IMPORT_ERROR", err.Error(), map[string]interface{}{
  870. "statementsExecuted": result.StatementsExecuted,
  871. "tablesCreated": result.TablesCreated,
  872. "rowsInserted": result.RowsInserted,
  873. "errors": result.Errors,
  874. })
  875. return
  876. }
  877. // Sync catalog after import
  878. exec.SyncCatalog()
  879. writeJSON(w, http.StatusOK, result, pretty)
  880. default:
  881. writeError(w, http.StatusBadRequest, "INVALID_FORMAT",
  882. fmt.Sprintf("Invalid format '%s'. Supported formats: sql, csv", format), nil)
  883. }
  884. }