2
0

handler.go 34 KB

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