2
0

handler.go 33 KB

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