handler.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  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 errors.Is(err, pgerror.ErrLockNotAvailable) {
  474. return &HTTPError{
  475. Status: http.StatusConflict,
  476. Code: pgerror.CodeLockNotAvailable,
  477. Message: message,
  478. }
  479. }
  480. if errors.Is(err, pgerror.ErrDeadlockDetected) {
  481. return &HTTPError{
  482. Status: http.StatusConflict,
  483. Code: pgerror.CodeDeadlockDetected,
  484. Message: message,
  485. }
  486. }
  487. if strings.Contains(message, "feature not supported:") {
  488. return &HTTPError{
  489. Status: http.StatusBadRequest,
  490. Code: "0A000",
  491. Message: message,
  492. }
  493. }
  494. if errors.Is(err, pgerror.ErrInvalidText) {
  495. return &HTTPError{
  496. Status: http.StatusBadRequest,
  497. Code: pgerror.CodeInvalidText,
  498. Message: message,
  499. }
  500. }
  501. if errors.Is(err, pgerror.ErrInvalidParameter) {
  502. return &HTTPError{
  503. Status: http.StatusBadRequest,
  504. Code: pgerror.CodeInvalidParameter,
  505. Message: message,
  506. }
  507. }
  508. if errors.Is(err, pgerror.ErrInvalidColumnReference) {
  509. return &HTTPError{
  510. Status: http.StatusBadRequest,
  511. Code: pgerror.CodeInvalidColumnReference,
  512. Message: message,
  513. }
  514. }
  515. var analysisErr *analyzer.AnalysisError
  516. if errors.Is(err, pgerror.ErrDatatypeMismatch) || (errors.As(err, &analysisErr) && analysisErr.Type == analyzer.ErrTypeMismatch) {
  517. return &HTTPError{
  518. Status: http.StatusBadRequest,
  519. Code: pgerror.CodeDatatypeMismatch,
  520. Message: message,
  521. }
  522. }
  523. if errors.Is(err, pgerror.ErrUndefinedTable) || (errors.As(err, &analysisErr) && analysisErr.Type == analyzer.ErrTableNotFound) {
  524. return &HTTPError{
  525. Status: http.StatusNotFound,
  526. Code: pgerror.CodeUndefinedTable,
  527. Message: message,
  528. }
  529. }
  530. return &HTTPError{
  531. Status: http.StatusInternalServerError,
  532. Code: "EXECUTION_ERROR",
  533. Message: message,
  534. }
  535. }
  536. // handleHealth handles GET /health
  537. func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
  538. resp := map[string]interface{}{
  539. "status": "ok",
  540. "version": version.String(),
  541. "uptime": time.Since(s.stats.StartTime).String(),
  542. }
  543. pretty := r.URL.Query().Get("pretty") == "true"
  544. writeJSON(w, http.StatusOK, resp, pretty)
  545. }
  546. // handleStats handles GET /stats
  547. func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) {
  548. // Get database from X-Database header
  549. dbName := r.Header.Get("X-Database")
  550. _, schema, _ := s.getExecutorForDatabase(dbName)
  551. var tables []string
  552. if schema != nil {
  553. tables, _ = schema.ListTables()
  554. }
  555. var avgQueryTime string
  556. if s.stats.QueriesExecuted > 0 {
  557. avgQueryTime = "N/A" // TODO: Track actual query times
  558. } else {
  559. avgQueryTime = "0ms"
  560. }
  561. resp := map[string]interface{}{
  562. "queriesExecuted": atomic.LoadInt64(&s.stats.QueriesExecuted),
  563. "queriesSuccess": atomic.LoadInt64(&s.stats.QueriesSuccess),
  564. "queriesError": atomic.LoadInt64(&s.stats.QueriesError),
  565. "tablesCount": len(tables),
  566. "avgQueryTime": avgQueryTime,
  567. "uptime": time.Since(s.stats.StartTime).String(),
  568. }
  569. pretty := r.URL.Query().Get("pretty") == "true"
  570. writeJSON(w, http.StatusOK, resp, pretty)
  571. }
  572. // handleTransactionBegin handles POST /transaction/begin
  573. func (s *Server) handleTransactionBegin(w http.ResponseWriter, r *http.Request) {
  574. if r.Method != http.MethodPost {
  575. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  576. return
  577. }
  578. // Get database from X-Database header
  579. dbName := r.Header.Get("X-Database")
  580. txID, _, err := s.beginTransaction(dbName)
  581. if err != nil {
  582. writeError(w, http.StatusInternalServerError, "TRANSACTION_ERROR", err.Error(), nil)
  583. return
  584. }
  585. resp := map[string]interface{}{
  586. "transactionId": txID,
  587. "status": "started",
  588. }
  589. pretty := r.URL.Query().Get("pretty") == "true"
  590. writeJSON(w, http.StatusOK, resp, pretty)
  591. }
  592. // handleTransactionCommit handles POST /transaction/commit
  593. func (s *Server) handleTransactionCommit(w http.ResponseWriter, r *http.Request) {
  594. if r.Method != http.MethodPost {
  595. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  596. return
  597. }
  598. var req TransactionRequest
  599. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  600. writeError(w, http.StatusBadRequest, "INVALID_JSON", "Invalid JSON in request body", nil)
  601. return
  602. }
  603. tx, ok := s.takeTransactionExecutor(req.TransactionID, r.Header.Get("X-Database"))
  604. if !ok {
  605. writeError(w, http.StatusNotFound, "TRANSACTION_NOT_FOUND", "unknown transaction ID", nil)
  606. return
  607. }
  608. defer tx.mu.Unlock()
  609. l := lexer.New("COMMIT")
  610. p := parser.New(l)
  611. stmt, _ := p.Parse()
  612. if _, err := tx.exec.Execute(stmt); err != nil {
  613. if errors.Is(err, storage.ErrSerialization) {
  614. writeError(w, http.StatusConflict, "SERIALIZATION_FAILURE", err.Error(), nil)
  615. } else if constraintErr := constraintViolationHTTPError(err); constraintErr != nil {
  616. writeError(w, constraintErr.Status, constraintErr.Code, constraintErr.Message, constraintErr.Details)
  617. } else {
  618. writeError(w, http.StatusBadRequest, "TRANSACTION_ERROR", err.Error(), nil)
  619. }
  620. return
  621. }
  622. resp := map[string]interface{}{
  623. "status": "committed",
  624. }
  625. pretty := r.URL.Query().Get("pretty") == "true"
  626. writeJSON(w, http.StatusOK, resp, pretty)
  627. }
  628. // substituteParams replaces ? placeholders with actual parameter values.
  629. // This is a simple implementation that handles basic SQL escaping.
  630. func substituteParams(sql string, params []interface{}) string {
  631. if len(params) == 0 {
  632. return sql
  633. }
  634. result := sql
  635. for _, param := range params {
  636. idx := strings.Index(result, "?")
  637. if idx == -1 {
  638. break
  639. }
  640. var replacement string
  641. switch v := param.(type) {
  642. case nil:
  643. replacement = "NULL"
  644. case string:
  645. // Escape single quotes in strings
  646. escaped := strings.ReplaceAll(v, "'", "''")
  647. replacement = "'" + escaped + "'"
  648. case int, int64, int32, int16, int8:
  649. replacement = fmt.Sprintf("%d", v)
  650. case float64, float32:
  651. replacement = fmt.Sprintf("%g", v)
  652. case bool:
  653. if v {
  654. replacement = "1"
  655. } else {
  656. replacement = "0"
  657. }
  658. default:
  659. // For other types, convert to string
  660. escaped := strings.ReplaceAll(fmt.Sprintf("%v", v), "'", "''")
  661. replacement = "'" + escaped + "'"
  662. }
  663. result = result[:idx] + replacement + result[idx+1:]
  664. }
  665. return result
  666. }
  667. // inferType infers SQL type from a Go value.
  668. func inferType(v interface{}) string {
  669. switch v.(type) {
  670. case nil:
  671. return "NULL"
  672. case int, int64, int32, int16, int8:
  673. return "INTEGER"
  674. case float64, float32:
  675. return "REAL"
  676. case string:
  677. return "TEXT"
  678. case []byte:
  679. return "BLOB"
  680. case bool:
  681. return "INTEGER"
  682. default:
  683. return "ANY"
  684. }
  685. }
  686. // handleTransactionRollback handles POST /transaction/rollback
  687. func (s *Server) handleTransactionRollback(w http.ResponseWriter, r *http.Request) {
  688. if r.Method != http.MethodPost {
  689. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  690. return
  691. }
  692. var req TransactionRequest
  693. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  694. writeError(w, http.StatusBadRequest, "INVALID_JSON", "Invalid JSON in request body", nil)
  695. return
  696. }
  697. tx, ok := s.takeTransactionExecutor(req.TransactionID, r.Header.Get("X-Database"))
  698. if !ok {
  699. writeError(w, http.StatusNotFound, "TRANSACTION_NOT_FOUND", "unknown transaction ID", nil)
  700. return
  701. }
  702. defer tx.mu.Unlock()
  703. l := lexer.New("ROLLBACK")
  704. p := parser.New(l)
  705. stmt, _ := p.Parse()
  706. if _, err := tx.exec.Execute(stmt); err != nil {
  707. writeError(w, http.StatusBadRequest, "TRANSACTION_ERROR", err.Error(), nil)
  708. return
  709. }
  710. resp := map[string]interface{}{
  711. "status": "rolled back",
  712. }
  713. pretty := r.URL.Query().Get("pretty") == "true"
  714. writeJSON(w, http.StatusOK, resp, pretty)
  715. }
  716. // handleMetrics handles GET /metrics in Prometheus format
  717. func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request) {
  718. if r.Method != http.MethodGet {
  719. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only GET method is allowed", nil)
  720. return
  721. }
  722. // Get database from X-Database header
  723. dbName := r.Header.Get("X-Database")
  724. _, schema, _ := s.getExecutorForDatabase(dbName)
  725. var tables []string
  726. if schema != nil {
  727. tables, _ = schema.ListTables()
  728. }
  729. uptime := time.Since(s.stats.StartTime).Seconds()
  730. queriesTotal := atomic.LoadInt64(&s.stats.QueriesExecuted)
  731. queriesSuccess := atomic.LoadInt64(&s.stats.QueriesSuccess)
  732. queriesError := atomic.LoadInt64(&s.stats.QueriesError)
  733. w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
  734. // Write Prometheus format metrics
  735. fmt.Fprintf(w, "# HELP pizzasql_queries_total Total number of queries executed\n")
  736. fmt.Fprintf(w, "# TYPE pizzasql_queries_total counter\n")
  737. fmt.Fprintf(w, "pizzasql_queries_total{status=\"success\"} %d\n", queriesSuccess)
  738. fmt.Fprintf(w, "pizzasql_queries_total{status=\"error\"} %d\n", queriesError)
  739. fmt.Fprintf(w, "\n")
  740. fmt.Fprintf(w, "# HELP pizzasql_queries_executed_total Total queries executed (all statuses)\n")
  741. fmt.Fprintf(w, "# TYPE pizzasql_queries_executed_total counter\n")
  742. fmt.Fprintf(w, "pizzasql_queries_executed_total %d\n", queriesTotal)
  743. fmt.Fprintf(w, "\n")
  744. fmt.Fprintf(w, "# HELP pizzasql_tables_count Number of tables in the database\n")
  745. fmt.Fprintf(w, "# TYPE pizzasql_tables_count gauge\n")
  746. fmt.Fprintf(w, "pizzasql_tables_count %d\n", len(tables))
  747. fmt.Fprintf(w, "\n")
  748. fmt.Fprintf(w, "# HELP pizzasql_uptime_seconds Server uptime in seconds\n")
  749. fmt.Fprintf(w, "# TYPE pizzasql_uptime_seconds gauge\n")
  750. fmt.Fprintf(w, "pizzasql_uptime_seconds %.2f\n", uptime)
  751. fmt.Fprintf(w, "\n")
  752. fmt.Fprintf(w, "# HELP pizzasql_info PizzaSQL server information\n")
  753. fmt.Fprintf(w, "# TYPE pizzasql_info gauge\n")
  754. fmt.Fprintf(w, "pizzasql_info{version=\"%s\"} 1\n", version.PrometheusLabel())
  755. }
  756. // handleExport handles GET /export
  757. func (s *Server) handleExport(w http.ResponseWriter, r *http.Request) {
  758. if r.Method != http.MethodGet {
  759. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only GET method is allowed", nil)
  760. return
  761. }
  762. // Get database from X-Database header
  763. dbName := strings.TrimSpace(r.Header.Get("X-Database"))
  764. _, schema, err := s.getExecutorForDatabase(dbName)
  765. if err != nil {
  766. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  767. return
  768. }
  769. // Get the table manager from the database instance
  770. dbInstance, err := s.dbManager.GetDatabase(dbName)
  771. if err != nil {
  772. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  773. return
  774. }
  775. // Get format parameter (default: sql)
  776. format := strings.ToLower(r.URL.Query().Get("format"))
  777. if format == "" {
  778. format = "sql"
  779. }
  780. tableName := r.URL.Query().Get("table")
  781. switch format {
  782. case "csv":
  783. // CSV export requires a single table
  784. if tableName == "" {
  785. writeError(w, http.StatusBadRequest, "TABLE_REQUIRED", "CSV export requires 'table' parameter", nil)
  786. return
  787. }
  788. csvOpts := csvexport.DefaultExportOptions()
  789. csvOpts.Table = tableName
  790. data, err := csvexport.ExportTableToBytes(schema, dbInstance.Table, csvOpts)
  791. if err != nil {
  792. writeError(w, http.StatusInternalServerError, "EXPORT_ERROR", err.Error(), nil)
  793. return
  794. }
  795. w.Header().Set("Content-Type", "text/csv")
  796. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s.csv\"", tableName))
  797. w.WriteHeader(http.StatusOK)
  798. w.Write(data)
  799. case "sql", "sqlite":
  800. // SQL export (also used for SQLite-compatible export)
  801. opts := sqlexport.DefaultExportOptions()
  802. // Specific table(s) to export
  803. if tableName != "" {
  804. opts.Tables = strings.Split(tableName, ",")
  805. }
  806. // Include data (default: true)
  807. if r.URL.Query().Get("schema_only") == "true" {
  808. opts.IncludeData = false
  809. }
  810. // Include DROP TABLE statements
  811. if r.URL.Query().Get("drop") == "true" {
  812. opts.DropTables = true
  813. }
  814. // Generate SQL export
  815. sql, err := sqlexport.ExportDatabase(schema, dbInstance.Table, opts)
  816. if err != nil {
  817. writeError(w, http.StatusInternalServerError, "EXPORT_ERROR", err.Error(), nil)
  818. return
  819. }
  820. // Determine filename and content type
  821. ext := "sql"
  822. contentType := "application/sql"
  823. if format == "sqlite" {
  824. ext = "sql" // Still SQL text, but sqlite-compatible
  825. }
  826. filename := schema.GetDatabaseName() + "_export." + ext
  827. if len(opts.Tables) == 1 {
  828. filename = opts.Tables[0] + "_export." + ext
  829. }
  830. w.Header().Set("Content-Type", contentType)
  831. w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
  832. w.WriteHeader(http.StatusOK)
  833. w.Write([]byte(sql))
  834. default:
  835. writeError(w, http.StatusBadRequest, "INVALID_FORMAT",
  836. fmt.Sprintf("Invalid format '%s'. Supported formats: sql, csv", format), nil)
  837. }
  838. }
  839. // handleImport handles POST /import
  840. func (s *Server) handleImport(w http.ResponseWriter, r *http.Request) {
  841. if r.Method != http.MethodPost {
  842. writeError(w, http.StatusMethodNotAllowed, "METHOD_NOT_ALLOWED", "Only POST method is allowed", nil)
  843. return
  844. }
  845. // Get database from X-Database header
  846. dbName := strings.TrimSpace(r.Header.Get("X-Database"))
  847. exec, schema, err := s.getExecutorForDatabase(dbName)
  848. if err != nil {
  849. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  850. return
  851. }
  852. // Get the table manager from the database instance
  853. dbInstance, err := s.dbManager.GetDatabase(dbName)
  854. if err != nil {
  855. writeError(w, http.StatusBadRequest, "DATABASE_ERROR", fmt.Sprintf("database not found: %s", dbName), nil)
  856. return
  857. }
  858. // Get format parameter (default: sql, can be auto-detected)
  859. format := strings.ToLower(r.URL.Query().Get("format"))
  860. tableName := r.URL.Query().Get("table")
  861. ignoreErrors := r.URL.Query().Get("ignore_errors") == "true"
  862. createTable := r.URL.Query().Get("create_table") == "true"
  863. pretty := r.URL.Query().Get("pretty") == "true"
  864. // Check content type
  865. contentType := r.Header.Get("Content-Type")
  866. var fileContent []byte
  867. var filename string
  868. if strings.HasPrefix(contentType, "multipart/form-data") {
  869. // Handle file upload
  870. if err := r.ParseMultipartForm(32 << 20); err != nil { // 32MB max
  871. writeError(w, http.StatusBadRequest, "INVALID_FORM", "Failed to parse multipart form: "+err.Error(), nil)
  872. return
  873. }
  874. file, header, err := r.FormFile("file")
  875. if err != nil {
  876. writeError(w, http.StatusBadRequest, "MISSING_FILE", "No file uploaded. Use 'file' field name.", nil)
  877. return
  878. }
  879. defer file.Close()
  880. filename = header.Filename
  881. // Read file content
  882. fileContent, err = io.ReadAll(file)
  883. if err != nil {
  884. writeError(w, http.StatusBadRequest, "READ_ERROR", "Failed to read uploaded file: "+err.Error(), nil)
  885. return
  886. }
  887. } else if strings.HasPrefix(contentType, "application/json") {
  888. // Handle JSON body with SQL content
  889. var req struct {
  890. SQL string `json:"sql"`
  891. }
  892. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  893. writeError(w, http.StatusBadRequest, "INVALID_JSON", "Invalid JSON in request body", nil)
  894. return
  895. }
  896. fileContent = []byte(req.SQL)
  897. } else if strings.HasPrefix(contentType, "text/plain") || strings.HasPrefix(contentType, "application/sql") || strings.HasPrefix(contentType, "text/csv") {
  898. // Handle raw content in body
  899. var err error
  900. fileContent, err = io.ReadAll(r.Body)
  901. if err != nil {
  902. writeError(w, http.StatusBadRequest, "READ_ERROR", "Failed to read request body: "+err.Error(), nil)
  903. return
  904. }
  905. // Auto-detect CSV from content type
  906. if strings.HasPrefix(contentType, "text/csv") && format == "" {
  907. format = "csv"
  908. }
  909. } else {
  910. writeError(w, http.StatusBadRequest, "INVALID_CONTENT_TYPE",
  911. "Content-Type must be multipart/form-data, application/json, text/plain, text/csv, or application/sql", nil)
  912. return
  913. }
  914. if len(fileContent) == 0 {
  915. writeError(w, http.StatusBadRequest, "EMPTY_CONTENT", "No content provided", nil)
  916. return
  917. }
  918. // Auto-detect format from filename extension if not specified
  919. if format == "" && filename != "" {
  920. lower := strings.ToLower(filename)
  921. if strings.HasSuffix(lower, ".csv") {
  922. format = "csv"
  923. } else if strings.HasSuffix(lower, ".db") || strings.HasSuffix(lower, ".sqlite") || strings.HasSuffix(lower, ".sqlite3") {
  924. format = "sqlite"
  925. }
  926. }
  927. // Detect binary SQLite from content-type
  928. if format == "" {
  929. ct := strings.ToLower(contentType)
  930. if strings.Contains(ct, "application/x-sqlite3") || strings.Contains(ct, "application/octet-stream") {
  931. format = "sqlite"
  932. }
  933. }
  934. // Check magic bytes: SQLite files start with "SQLite format 3\000"
  935. if format == "" && len(fileContent) >= 16 && string(fileContent[:15]) == "SQLite format 3" {
  936. format = "sqlite"
  937. }
  938. if format == "" {
  939. format = "sql"
  940. }
  941. switch format {
  942. case "csv":
  943. // CSV import requires table name
  944. if tableName == "" {
  945. writeError(w, http.StatusBadRequest, "TABLE_REQUIRED", "CSV import requires 'table' parameter", nil)
  946. return
  947. }
  948. csvOpts := csvimport.DefaultImportOptions()
  949. csvOpts.TableName = tableName
  950. csvOpts.IgnoreErrors = ignoreErrors
  951. csvOpts.CreateTable = createTable
  952. result, err := csvimport.ImportCSV(strings.NewReader(string(fileContent)), schema, dbInstance.Table, csvOpts)
  953. if err != nil && !ignoreErrors {
  954. writeError(w, http.StatusBadRequest, "IMPORT_ERROR", err.Error(), map[string]interface{}{
  955. "rowsImported": result.RowsImported,
  956. "rowsSkipped": result.RowsSkipped,
  957. "tableCreated": result.TableCreated,
  958. "errors": result.Errors,
  959. })
  960. return
  961. }
  962. // Sync catalog after import
  963. exec.SyncCatalog()
  964. writeJSON(w, http.StatusOK, result, pretty)
  965. case "sqlite":
  966. // Binary SQLite .db import
  967. opts := sqliteimport.DefaultImportOptions()
  968. opts.CreateTables = r.URL.Query().Get("create_tables") != "false"
  969. opts.IgnoreErrors = ignoreErrors
  970. result, err := sqliteimport.ImportSQLiteBytes(fileContent, exec, opts)
  971. if err != nil && !ignoreErrors {
  972. writeError(w, http.StatusBadRequest, "IMPORT_ERROR", err.Error(), map[string]interface{}{
  973. "tablesCreated": result.TablesCreated,
  974. "rowsInserted": result.RowsInserted,
  975. "errors": result.Errors,
  976. })
  977. return
  978. }
  979. exec.SyncCatalog()
  980. writeJSON(w, http.StatusOK, result, pretty)
  981. case "sql":
  982. // SQL text import
  983. opts := sqlimport.DefaultImportOptions()
  984. opts.IgnoreErrors = ignoreErrors
  985. result, err := sqlimport.ImportSQL(exec, string(fileContent), opts)
  986. if err != nil && !ignoreErrors {
  987. writeError(w, http.StatusBadRequest, "IMPORT_ERROR", err.Error(), map[string]interface{}{
  988. "statementsExecuted": result.StatementsExecuted,
  989. "tablesCreated": result.TablesCreated,
  990. "rowsInserted": result.RowsInserted,
  991. "errors": result.Errors,
  992. })
  993. return
  994. }
  995. // Sync catalog after import
  996. exec.SyncCatalog()
  997. writeJSON(w, http.StatusOK, result, pretty)
  998. default:
  999. writeError(w, http.StatusBadRequest, "INVALID_FORMAT",
  1000. fmt.Sprintf("Invalid format '%s'. Supported formats: sql, csv", format), nil)
  1001. }
  1002. }