handler.go 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  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 if constraintErr := constraintViolationHTTPError(err); constraintErr != nil {
  259. writeError(w, constraintErr.Status, constraintErr.Code, constraintErr.Message, constraintErr.Details)
  260. } else {
  261. writeError(w, http.StatusBadRequest, "TRANSACTION_ERROR", err.Error(), nil)
  262. }
  263. return
  264. }
  265. }
  266. } else if executeErr != nil {
  267. httpErr := sqlStateHTTPError(executeErr)
  268. writeError(w, httpErr.Status, httpErr.Code, httpErr.Message, httpErr.Details)
  269. return
  270. }
  271. resp := &ExecuteResponse{
  272. Results: results,
  273. ExecutionTime: time.Since(start).String(),
  274. }
  275. writeJSON(w, http.StatusOK, resp, pretty)
  276. }
  277. // handleSchemaTables handles GET /schema/tables
  278. func (s *Server) handleSchemaTables(w http.ResponseWriter, r *http.Request) {
  279. if r.Method != http.MethodGet {
  280. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only GET method is allowed", nil)
  281. return
  282. }
  283. // Get database from X-Database header (trim whitespace)
  284. dbName := strings.TrimSpace(r.Header.Get("X-Database"))
  285. _, schema, err := s.getExecutorForDatabase(dbName)
  286. if err != nil {
  287. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  288. return
  289. }
  290. actualDB := schema.GetDatabaseName()
  291. tables, err := schema.ListTables()
  292. if err != nil {
  293. writeError(w, http.StatusInternalServerError, "SCHEMA_ERROR", err.Error(), nil)
  294. return
  295. }
  296. // Include the actual database name and requested name in the response for verification
  297. resp := map[string]interface{}{
  298. "database": actualDB,
  299. "requested_database": dbName,
  300. "tables": tables,
  301. }
  302. pretty := r.URL.Query().Get("pretty") == "true"
  303. writeJSON(w, http.StatusOK, resp, pretty)
  304. }
  305. // handleSchemaTable handles GET /schema/tables/{table}
  306. func (s *Server) handleSchemaTable(w http.ResponseWriter, r *http.Request) {
  307. if r.Method != http.MethodGet {
  308. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only GET method is allowed", nil)
  309. return
  310. }
  311. // Get database from X-Database header
  312. dbName := r.Header.Get("X-Database")
  313. _, schemaManager, err := s.getExecutorForDatabase(dbName)
  314. if err != nil {
  315. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  316. return
  317. }
  318. // Extract table name from path
  319. path := strings.TrimPrefix(r.URL.Path, "/schema/tables/")
  320. tableName := strings.TrimSpace(path)
  321. if tableName == "" {
  322. writeError(w, http.StatusBadRequest, "MISSING_TABLE_NAME", "Table name is required", nil)
  323. return
  324. }
  325. schema, err := schemaManager.GetSchema(tableName)
  326. if err != nil {
  327. writeError(w, http.StatusNotFound, "TABLE_NOT_FOUND", fmt.Sprintf("Table '%s' not found", tableName), nil)
  328. return
  329. }
  330. columns := make([]map[string]interface{}, len(schema.Columns))
  331. for i, col := range schema.Columns {
  332. columns[i] = map[string]interface{}{
  333. "name": col.Name,
  334. "type": col.Type,
  335. "nullable": col.Nullable,
  336. "primaryKey": col.PrimaryKey,
  337. "default": col.DefaultLiteral(),
  338. }
  339. }
  340. resp := map[string]interface{}{
  341. "name": schema.Name,
  342. "columns": columns,
  343. }
  344. pretty := r.URL.Query().Get("pretty") == "true"
  345. writeJSON(w, http.StatusOK, resp, pretty)
  346. }
  347. // handleCapabilities serves the machine-readable capability document so clients
  348. // can discover supported SQL surface for this engine build.
  349. func (s *Server) handleCapabilities(w http.ResponseWriter, r *http.Request) {
  350. pretty := r.URL.Query().Get("pretty") == "true"
  351. writeJSON(w, http.StatusOK, capabilities.Current(), pretty)
  352. }
  353. // handleVersion reports the build identity and the protocol compatibility
  354. // floor separately, so clients can pin behavior to a specific engine build.
  355. func (s *Server) handleVersion(w http.ResponseWriter, r *http.Request) {
  356. resp := map[string]interface{}{
  357. "name": "pizzasql",
  358. "version": version.String(),
  359. "commit": version.Commit,
  360. "date": version.Date,
  361. "dirty": version.Dirty != "",
  362. "postgres_compat": version.PostgreSQLCompatVersion,
  363. "sqlite_compat": executor.SQLiteCompatVersion,
  364. }
  365. pretty := r.URL.Query().Get("pretty") == "true"
  366. writeJSON(w, http.StatusOK, resp, pretty)
  367. }
  368. // constraintViolationHTTPError maps a row-constraint violation onto the same
  369. // SQLSTATE response the PostgreSQL endpoint reports, and returns nil for any
  370. // other error. Transaction endpoints use it for a deferred unique, not-null, or
  371. // check failure at COMMIT while keeping their generic TRANSACTION_ERROR
  372. // fallback for errors that are not constraint violations.
  373. func constraintViolationHTTPError(err error) *HTTPError {
  374. var checkErr *storage.CheckViolationError
  375. var notNullErr *storage.NotNullViolationError
  376. var uniqueErr *storage.UniqueViolationError
  377. var primaryKeyErr *storage.PrimaryKeyViolationError
  378. switch {
  379. case errors.As(err, &checkErr):
  380. return &HTTPError{
  381. Status: http.StatusBadRequest,
  382. Code: "23514",
  383. Message: err.Error(),
  384. Details: map[string]interface{}{"constraint": checkErr.Constraint},
  385. }
  386. case errors.As(err, &notNullErr):
  387. return &HTTPError{
  388. Status: http.StatusBadRequest,
  389. Code: "23502",
  390. Message: err.Error(),
  391. }
  392. case errors.As(err, &uniqueErr):
  393. return &HTTPError{
  394. Status: http.StatusConflict,
  395. Code: "23505",
  396. Message: err.Error(),
  397. Details: map[string]interface{}{"constraint": uniqueErr.Constraint},
  398. }
  399. case errors.As(err, &primaryKeyErr):
  400. return &HTTPError{
  401. Status: http.StatusConflict,
  402. Code: "23505",
  403. Message: err.Error(),
  404. }
  405. default:
  406. return nil
  407. }
  408. }
  409. // sqlStateHTTPError maps engine errors onto the same SQLSTATE codes the
  410. // PostgreSQL endpoint reports. Typed constraint violations map first; the
  411. // executor also returns plain errors on released builds, so the
  412. // unique-violation, not-null, and unsupported-feature markers are matched on
  413. // their stable message prefixes as a fallback.
  414. func sqlStateHTTPError(err error) *HTTPError {
  415. if err == nil {
  416. return nil
  417. }
  418. if typed := constraintViolationHTTPError(err); typed != nil {
  419. return typed
  420. }
  421. message := err.Error()
  422. if strings.HasPrefix(message, "UNIQUE constraint failed: ") {
  423. constraint := strings.TrimPrefix(message, "UNIQUE constraint failed: ")
  424. return &HTTPError{
  425. Status: http.StatusConflict,
  426. Code: "23505",
  427. Message: message,
  428. Details: map[string]interface{}{"constraint": constraint},
  429. }
  430. }
  431. if strings.HasPrefix(message, "NOT NULL constraint failed: ") {
  432. return &HTTPError{
  433. Status: http.StatusBadRequest,
  434. Code: "23502",
  435. Message: message,
  436. }
  437. }
  438. if strings.HasPrefix(message, "CHECK constraint failed: ") {
  439. constraint := strings.TrimPrefix(message, "CHECK constraint failed: ")
  440. return &HTTPError{
  441. Status: http.StatusBadRequest,
  442. Code: "23514",
  443. Message: message,
  444. Details: map[string]interface{}{"constraint": constraint},
  445. }
  446. }
  447. if errors.Is(err, storage.ErrSerialization) {
  448. return &HTTPError{
  449. Status: http.StatusConflict,
  450. Code: "40001",
  451. Message: message,
  452. }
  453. }
  454. if strings.Contains(message, "feature not supported:") {
  455. return &HTTPError{
  456. Status: http.StatusBadRequest,
  457. Code: "0A000",
  458. Message: message,
  459. }
  460. }
  461. return &HTTPError{
  462. Status: http.StatusInternalServerError,
  463. Code: "EXECUTION_ERROR",
  464. Message: message,
  465. }
  466. }
  467. // handleHealth handles GET /health
  468. func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
  469. resp := map[string]interface{}{
  470. "status": "ok",
  471. "version": version.String(),
  472. "uptime": time.Since(s.stats.StartTime).String(),
  473. }
  474. pretty := r.URL.Query().Get("pretty") == "true"
  475. writeJSON(w, http.StatusOK, resp, pretty)
  476. }
  477. // handleStats handles GET /stats
  478. func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) {
  479. // Get database from X-Database header
  480. dbName := r.Header.Get("X-Database")
  481. _, schema, _ := s.getExecutorForDatabase(dbName)
  482. var tables []string
  483. if schema != nil {
  484. tables, _ = schema.ListTables()
  485. }
  486. var avgQueryTime string
  487. if s.stats.QueriesExecuted > 0 {
  488. avgQueryTime = "N/A" // TODO: Track actual query times
  489. } else {
  490. avgQueryTime = "0ms"
  491. }
  492. resp := map[string]interface{}{
  493. "queriesExecuted": atomic.LoadInt64(&s.stats.QueriesExecuted),
  494. "queriesSuccess": atomic.LoadInt64(&s.stats.QueriesSuccess),
  495. "queriesError": atomic.LoadInt64(&s.stats.QueriesError),
  496. "tablesCount": len(tables),
  497. "avgQueryTime": avgQueryTime,
  498. "uptime": time.Since(s.stats.StartTime).String(),
  499. }
  500. pretty := r.URL.Query().Get("pretty") == "true"
  501. writeJSON(w, http.StatusOK, resp, pretty)
  502. }
  503. // handleTransactionBegin handles POST /transaction/begin
  504. func (s *Server) handleTransactionBegin(w http.ResponseWriter, r *http.Request) {
  505. if r.Method != http.MethodPost {
  506. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  507. return
  508. }
  509. // Get database from X-Database header
  510. dbName := r.Header.Get("X-Database")
  511. txID, _, err := s.beginTransaction(dbName)
  512. if err != nil {
  513. writeError(w, http.StatusInternalServerError, "TRANSACTION_ERROR", err.Error(), nil)
  514. return
  515. }
  516. resp := map[string]interface{}{
  517. "transactionId": txID,
  518. "status": "started",
  519. }
  520. pretty := r.URL.Query().Get("pretty") == "true"
  521. writeJSON(w, http.StatusOK, resp, pretty)
  522. }
  523. // handleTransactionCommit handles POST /transaction/commit
  524. func (s *Server) handleTransactionCommit(w http.ResponseWriter, r *http.Request) {
  525. if r.Method != http.MethodPost {
  526. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  527. return
  528. }
  529. var req TransactionRequest
  530. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  531. writeError(w, http.StatusBadRequest, "INVALID_JSON", "Invalid JSON in request body", nil)
  532. return
  533. }
  534. tx, ok := s.takeTransactionExecutor(req.TransactionID, r.Header.Get("X-Database"))
  535. if !ok {
  536. writeError(w, http.StatusNotFound, "TRANSACTION_NOT_FOUND", "unknown transaction ID", nil)
  537. return
  538. }
  539. defer tx.mu.Unlock()
  540. l := lexer.New("COMMIT")
  541. p := parser.New(l)
  542. stmt, _ := p.Parse()
  543. if _, err := tx.exec.Execute(stmt); err != nil {
  544. if errors.Is(err, storage.ErrSerialization) {
  545. writeError(w, http.StatusConflict, "SERIALIZATION_FAILURE", err.Error(), nil)
  546. } else if constraintErr := constraintViolationHTTPError(err); constraintErr != nil {
  547. writeError(w, constraintErr.Status, constraintErr.Code, constraintErr.Message, constraintErr.Details)
  548. } else {
  549. writeError(w, http.StatusBadRequest, "TRANSACTION_ERROR", err.Error(), nil)
  550. }
  551. return
  552. }
  553. resp := map[string]interface{}{
  554. "status": "committed",
  555. }
  556. pretty := r.URL.Query().Get("pretty") == "true"
  557. writeJSON(w, http.StatusOK, resp, pretty)
  558. }
  559. // substituteParams replaces ? placeholders with actual parameter values.
  560. // This is a simple implementation that handles basic SQL escaping.
  561. func substituteParams(sql string, params []interface{}) string {
  562. if len(params) == 0 {
  563. return sql
  564. }
  565. result := sql
  566. for _, param := range params {
  567. idx := strings.Index(result, "?")
  568. if idx == -1 {
  569. break
  570. }
  571. var replacement string
  572. switch v := param.(type) {
  573. case nil:
  574. replacement = "NULL"
  575. case string:
  576. // Escape single quotes in strings
  577. escaped := strings.ReplaceAll(v, "'", "''")
  578. replacement = "'" + escaped + "'"
  579. case int, int64, int32, int16, int8:
  580. replacement = fmt.Sprintf("%d", v)
  581. case float64, float32:
  582. replacement = fmt.Sprintf("%g", v)
  583. case bool:
  584. if v {
  585. replacement = "1"
  586. } else {
  587. replacement = "0"
  588. }
  589. default:
  590. // For other types, convert to string
  591. escaped := strings.ReplaceAll(fmt.Sprintf("%v", v), "'", "''")
  592. replacement = "'" + escaped + "'"
  593. }
  594. result = result[:idx] + replacement + result[idx+1:]
  595. }
  596. return result
  597. }
  598. // inferType infers SQL type from a Go value.
  599. func inferType(v interface{}) string {
  600. switch v.(type) {
  601. case nil:
  602. return "NULL"
  603. case int, int64, int32, int16, int8:
  604. return "INTEGER"
  605. case float64, float32:
  606. return "REAL"
  607. case string:
  608. return "TEXT"
  609. case []byte:
  610. return "BLOB"
  611. case bool:
  612. return "INTEGER"
  613. default:
  614. return "ANY"
  615. }
  616. }
  617. // handleTransactionRollback handles POST /transaction/rollback
  618. func (s *Server) handleTransactionRollback(w http.ResponseWriter, r *http.Request) {
  619. if r.Method != http.MethodPost {
  620. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  621. return
  622. }
  623. var req TransactionRequest
  624. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  625. writeError(w, http.StatusBadRequest, "INVALID_JSON", "Invalid JSON in request body", nil)
  626. return
  627. }
  628. tx, ok := s.takeTransactionExecutor(req.TransactionID, r.Header.Get("X-Database"))
  629. if !ok {
  630. writeError(w, http.StatusNotFound, "TRANSACTION_NOT_FOUND", "unknown transaction ID", nil)
  631. return
  632. }
  633. defer tx.mu.Unlock()
  634. l := lexer.New("ROLLBACK")
  635. p := parser.New(l)
  636. stmt, _ := p.Parse()
  637. if _, err := tx.exec.Execute(stmt); err != nil {
  638. writeError(w, http.StatusBadRequest, "TRANSACTION_ERROR", err.Error(), nil)
  639. return
  640. }
  641. resp := map[string]interface{}{
  642. "status": "rolled back",
  643. }
  644. pretty := r.URL.Query().Get("pretty") == "true"
  645. writeJSON(w, http.StatusOK, resp, pretty)
  646. }
  647. // handleMetrics handles GET /metrics in Prometheus format
  648. func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request) {
  649. if r.Method != http.MethodGet {
  650. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only GET method is allowed", nil)
  651. return
  652. }
  653. // Get database from X-Database header
  654. dbName := r.Header.Get("X-Database")
  655. _, schema, _ := s.getExecutorForDatabase(dbName)
  656. var tables []string
  657. if schema != nil {
  658. tables, _ = schema.ListTables()
  659. }
  660. uptime := time.Since(s.stats.StartTime).Seconds()
  661. queriesTotal := atomic.LoadInt64(&s.stats.QueriesExecuted)
  662. queriesSuccess := atomic.LoadInt64(&s.stats.QueriesSuccess)
  663. queriesError := atomic.LoadInt64(&s.stats.QueriesError)
  664. w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
  665. // Write Prometheus format metrics
  666. fmt.Fprintf(w, "# HELP pizzasql_queries_total Total number of queries executed\n")
  667. fmt.Fprintf(w, "# TYPE pizzasql_queries_total counter\n")
  668. fmt.Fprintf(w, "pizzasql_queries_total{status=\"success\"} %d\n", queriesSuccess)
  669. fmt.Fprintf(w, "pizzasql_queries_total{status=\"error\"} %d\n", queriesError)
  670. fmt.Fprintf(w, "\n")
  671. fmt.Fprintf(w, "# HELP pizzasql_queries_executed_total Total queries executed (all statuses)\n")
  672. fmt.Fprintf(w, "# TYPE pizzasql_queries_executed_total counter\n")
  673. fmt.Fprintf(w, "pizzasql_queries_executed_total %d\n", queriesTotal)
  674. fmt.Fprintf(w, "\n")
  675. fmt.Fprintf(w, "# HELP pizzasql_tables_count Number of tables in the database\n")
  676. fmt.Fprintf(w, "# TYPE pizzasql_tables_count gauge\n")
  677. fmt.Fprintf(w, "pizzasql_tables_count %d\n", len(tables))
  678. fmt.Fprintf(w, "\n")
  679. fmt.Fprintf(w, "# HELP pizzasql_uptime_seconds Server uptime in seconds\n")
  680. fmt.Fprintf(w, "# TYPE pizzasql_uptime_seconds gauge\n")
  681. fmt.Fprintf(w, "pizzasql_uptime_seconds %.2f\n", uptime)
  682. fmt.Fprintf(w, "\n")
  683. fmt.Fprintf(w, "# HELP pizzasql_info PizzaSQL server information\n")
  684. fmt.Fprintf(w, "# TYPE pizzasql_info gauge\n")
  685. fmt.Fprintf(w, "pizzasql_info{version=\"%s\"} 1\n", version.PrometheusLabel())
  686. }
  687. // handleExport handles GET /export
  688. func (s *Server) handleExport(w http.ResponseWriter, r *http.Request) {
  689. if r.Method != http.MethodGet {
  690. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only GET method is allowed", nil)
  691. return
  692. }
  693. // Get database from X-Database header
  694. dbName := strings.TrimSpace(r.Header.Get("X-Database"))
  695. _, schema, err := s.getExecutorForDatabase(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 the table manager from the database instance
  701. dbInstance, err := s.dbManager.GetDatabase(dbName)
  702. if err != nil {
  703. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  704. return
  705. }
  706. // Get format parameter (default: sql)
  707. format := strings.ToLower(r.URL.Query().Get("format"))
  708. if format == "" {
  709. format = "sql"
  710. }
  711. tableName := r.URL.Query().Get("table")
  712. switch format {
  713. case "csv":
  714. // CSV export requires a single table
  715. if tableName == "" {
  716. writeError(w, http.StatusBadRequest, "TABLE_REQUIRED", "CSV export requires 'table' parameter", nil)
  717. return
  718. }
  719. csvOpts := csvexport.DefaultExportOptions()
  720. csvOpts.Table = tableName
  721. data, err := csvexport.ExportTableToBytes(schema, dbInstance.Table, csvOpts)
  722. if err != nil {
  723. writeError(w, http.StatusInternalServerError, "EXPORT_ERROR", err.Error(), nil)
  724. return
  725. }
  726. w.Header().Set("Content-Type", "text/csv")
  727. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s.csv\"", tableName))
  728. w.WriteHeader(http.StatusOK)
  729. w.Write(data)
  730. case "sql", "sqlite":
  731. // SQL export (also used for SQLite-compatible export)
  732. opts := sqlexport.DefaultExportOptions()
  733. // Specific table(s) to export
  734. if tableName != "" {
  735. opts.Tables = strings.Split(tableName, ",")
  736. }
  737. // Include data (default: true)
  738. if r.URL.Query().Get("schema_only") == "true" {
  739. opts.IncludeData = false
  740. }
  741. // Include DROP TABLE statements
  742. if r.URL.Query().Get("drop") == "true" {
  743. opts.DropTables = true
  744. }
  745. // Generate SQL export
  746. sql, err := sqlexport.ExportDatabase(schema, dbInstance.Table, opts)
  747. if err != nil {
  748. writeError(w, http.StatusInternalServerError, "EXPORT_ERROR", err.Error(), nil)
  749. return
  750. }
  751. // Determine filename and content type
  752. ext := "sql"
  753. contentType := "application/sql"
  754. if format == "sqlite" {
  755. ext = "sql" // Still SQL text, but sqlite-compatible
  756. }
  757. filename := schema.GetDatabaseName() + "_export." + ext
  758. if len(opts.Tables) == 1 {
  759. filename = opts.Tables[0] + "_export." + ext
  760. }
  761. w.Header().Set("Content-Type", contentType)
  762. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
  763. w.WriteHeader(http.StatusOK)
  764. w.Write([]byte(sql))
  765. default:
  766. writeError(w, http.StatusBadRequest, "INVALID_FORMAT",
  767. fmt.Sprintf("Invalid format '%s'. Supported formats: sql, csv", format), nil)
  768. }
  769. }
  770. // handleImport handles POST /import
  771. func (s *Server) handleImport(w http.ResponseWriter, r *http.Request) {
  772. if r.Method != http.MethodPost {
  773. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  774. return
  775. }
  776. // Get database from X-Database header
  777. dbName := strings.TrimSpace(r.Header.Get("X-Database"))
  778. exec, schema, err := s.getExecutorForDatabase(dbName)
  779. if err != nil {
  780. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  781. return
  782. }
  783. // Get the table manager from the database instance
  784. dbInstance, err := s.dbManager.GetDatabase(dbName)
  785. if err != nil {
  786. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  787. return
  788. }
  789. // Get format parameter (default: sql, can be auto-detected)
  790. format := strings.ToLower(r.URL.Query().Get("format"))
  791. tableName := r.URL.Query().Get("table")
  792. ignoreErrors := r.URL.Query().Get("ignore_errors") == "true"
  793. createTable := r.URL.Query().Get("create_table") == "true"
  794. pretty := r.URL.Query().Get("pretty") == "true"
  795. // Check content type
  796. contentType := r.Header.Get("Content-Type")
  797. var fileContent []byte
  798. var filename string
  799. if strings.HasPrefix(contentType, "multipart/form-data") {
  800. // Handle file upload
  801. if err := r.ParseMultipartForm(32 << 20); err != nil { // 32MB max
  802. writeError(w, http.StatusBadRequest, "INVALID_FORM", "Failed to parse multipart form: "+err.Error(), nil)
  803. return
  804. }
  805. file, header, err := r.FormFile("file")
  806. if err != nil {
  807. writeError(w, http.StatusBadRequest, "MISSING_FILE", "No file uploaded. Use 'file' field name.", nil)
  808. return
  809. }
  810. defer file.Close()
  811. filename = header.Filename
  812. // Read file content
  813. fileContent, err = io.ReadAll(file)
  814. if err != nil {
  815. writeError(w, http.StatusBadRequest, "READ_ERROR", "Failed to read uploaded file: "+err.Error(), nil)
  816. return
  817. }
  818. } else if strings.HasPrefix(contentType, "application/json") {
  819. // Handle JSON body with SQL content
  820. var req struct {
  821. SQL string `json:"sql"`
  822. }
  823. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  824. writeError(w, http.StatusBadRequest, "INVALID_JSON", "Invalid JSON in request body", nil)
  825. return
  826. }
  827. fileContent = []byte(req.SQL)
  828. } else if strings.HasPrefix(contentType, "text/plain") || strings.HasPrefix(contentType, "application/sql") || strings.HasPrefix(contentType, "text/csv") {
  829. // Handle raw content in body
  830. var err error
  831. fileContent, err = io.ReadAll(r.Body)
  832. if err != nil {
  833. writeError(w, http.StatusBadRequest, "READ_ERROR", "Failed to read request body: "+err.Error(), nil)
  834. return
  835. }
  836. // Auto-detect CSV from content type
  837. if strings.HasPrefix(contentType, "text/csv") && format == "" {
  838. format = "csv"
  839. }
  840. } else {
  841. writeError(w, http.StatusBadRequest, "INVALID_CONTENT_TYPE",
  842. "Content-Type must be multipart/form-data, application/json, text/plain, text/csv, or application/sql", nil)
  843. return
  844. }
  845. if len(fileContent) == 0 {
  846. writeError(w, http.StatusBadRequest, "EMPTY_CONTENT", "No content provided", nil)
  847. return
  848. }
  849. // Auto-detect format from filename extension if not specified
  850. if format == "" && filename != "" {
  851. lower := strings.ToLower(filename)
  852. if strings.HasSuffix(lower, ".csv") {
  853. format = "csv"
  854. } else if strings.HasSuffix(lower, ".db") || strings.HasSuffix(lower, ".sqlite") || strings.HasSuffix(lower, ".sqlite3") {
  855. format = "sqlite"
  856. }
  857. }
  858. // Detect binary SQLite from content-type
  859. if format == "" {
  860. ct := strings.ToLower(contentType)
  861. if strings.Contains(ct, "application/x-sqlite3") || strings.Contains(ct, "application/octet-stream") {
  862. format = "sqlite"
  863. }
  864. }
  865. // Check magic bytes: SQLite files start with "SQLite format 3\000"
  866. if format == "" && len(fileContent) >= 16 && string(fileContent[:15]) == "SQLite format 3" {
  867. format = "sqlite"
  868. }
  869. if format == "" {
  870. format = "sql"
  871. }
  872. switch format {
  873. case "csv":
  874. // CSV import requires table name
  875. if tableName == "" {
  876. writeError(w, http.StatusBadRequest, "TABLE_REQUIRED", "CSV import requires 'table' parameter", nil)
  877. return
  878. }
  879. csvOpts := csvimport.DefaultImportOptions()
  880. csvOpts.TableName = tableName
  881. csvOpts.IgnoreErrors = ignoreErrors
  882. csvOpts.CreateTable = createTable
  883. result, err := csvimport.ImportCSV(strings.NewReader(string(fileContent)), schema, dbInstance.Table, csvOpts)
  884. if err != nil && !ignoreErrors {
  885. writeError(w, http.StatusBadRequest, "IMPORT_ERROR", err.Error(), map[string]interface{}{
  886. "rowsImported": result.RowsImported,
  887. "rowsSkipped": result.RowsSkipped,
  888. "tableCreated": result.TableCreated,
  889. "errors": result.Errors,
  890. })
  891. return
  892. }
  893. // Sync catalog after import
  894. exec.SyncCatalog()
  895. writeJSON(w, http.StatusOK, result, pretty)
  896. case "sqlite":
  897. // Binary SQLite .db import
  898. opts := sqliteimport.DefaultImportOptions()
  899. opts.CreateTables = r.URL.Query().Get("create_tables") != "false"
  900. opts.IgnoreErrors = ignoreErrors
  901. result, err := sqliteimport.ImportSQLiteBytes(fileContent, exec, opts)
  902. if err != nil && !ignoreErrors {
  903. writeError(w, http.StatusBadRequest, "IMPORT_ERROR", err.Error(), map[string]interface{}{
  904. "tablesCreated": result.TablesCreated,
  905. "rowsInserted": result.RowsInserted,
  906. "errors": result.Errors,
  907. })
  908. return
  909. }
  910. exec.SyncCatalog()
  911. writeJSON(w, http.StatusOK, result, pretty)
  912. case "sql":
  913. // SQL text import
  914. opts := sqlimport.DefaultImportOptions()
  915. opts.IgnoreErrors = ignoreErrors
  916. result, err := sqlimport.ImportSQL(exec, string(fileContent), opts)
  917. if err != nil && !ignoreErrors {
  918. writeError(w, http.StatusBadRequest, "IMPORT_ERROR", err.Error(), map[string]interface{}{
  919. "statementsExecuted": result.StatementsExecuted,
  920. "tablesCreated": result.TablesCreated,
  921. "rowsInserted": result.RowsInserted,
  922. "errors": result.Errors,
  923. })
  924. return
  925. }
  926. // Sync catalog after import
  927. exec.SyncCatalog()
  928. writeJSON(w, http.StatusOK, result, pretty)
  929. default:
  930. writeError(w, http.StatusBadRequest, "INVALID_FORMAT",
  931. fmt.Sprintf("Invalid format '%s'. Supported formats: sql, csv", format), nil)
  932. }
  933. }