2
0

sqlstate_test.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. package httpserver
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "net/http/httptest"
  8. "strings"
  9. "testing"
  10. "github.com/danfragoso/pizzasql-next/pkg/storage"
  11. )
  12. type httpErrorBody struct {
  13. Error struct {
  14. Code string `json:"code"`
  15. Message string `json:"message"`
  16. Details map[string]interface{} `json:"details"`
  17. } `json:"error"`
  18. }
  19. func TestHTTPUniqueViolationReturns23505(t *testing.T) {
  20. server := setupKVTestServer(t)
  21. queryHTTP(t, server, "CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE)")
  22. queryHTTP(t, server, "INSERT INTO users (id, email) VALUES (1, 'a@x')")
  23. body, _ := json.Marshal(QueryRequest{SQL: "INSERT INTO users (id, email) VALUES (2, 'a@x')"})
  24. r := httptest.NewRequest(http.MethodPost, "/query", strings.NewReader(string(body)))
  25. w := httptest.NewRecorder()
  26. server.handleQuery(w, r)
  27. if w.Code != http.StatusConflict {
  28. t.Fatalf("status = %d, want 409; body %s", w.Code, w.Body.String())
  29. }
  30. var resp httpErrorBody
  31. if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
  32. t.Fatalf("decode: %v", err)
  33. }
  34. if resp.Error.Code != "23505" {
  35. t.Fatalf("code = %q, want 23505", resp.Error.Code)
  36. }
  37. constraint, _ := resp.Error.Details["constraint"].(string)
  38. if constraint == "" || !strings.Contains(resp.Error.Message, constraint) {
  39. t.Fatalf("details.constraint = %q, message = %q", constraint, resp.Error.Message)
  40. }
  41. }
  42. // A constraint the commit discovers must report its SQLSTATE instead of the
  43. // generic TRANSACTION_ERROR the transaction endpoints use for other failures.
  44. func TestHTTPCommitCheckViolationReturns23514(t *testing.T) {
  45. s := newTestDBServer(t)
  46. if w := postQuery(t, s, "CREATE TABLE t (id INTEGER PRIMARY KEY)"); w.Code != http.StatusOK {
  47. t.Fatalf("create table: %d %s", w.Code, w.Body.String())
  48. }
  49. txID := beginTransaction(t, s, "")
  50. if w := postTransactionQuery(t, s, txID, "INSERT INTO t (id) VALUES (1)"); w.Code != http.StatusOK {
  51. t.Fatalf("staged insert: %d %s", w.Code, w.Body.String())
  52. }
  53. // A second session publishes the constraint the staged row will violate.
  54. if w := postQuery(t, s, "ALTER TABLE t ADD COLUMN qty INTEGER DEFAULT -1 CHECK (qty >= 0)"); w.Code != http.StatusOK {
  55. t.Fatalf("add column: %d %s", w.Code, w.Body.String())
  56. }
  57. body, _ := json.Marshal(TransactionRequest{TransactionID: txID})
  58. r := httptest.NewRequest(http.MethodPost, "/transaction/commit", strings.NewReader(string(body)))
  59. w := httptest.NewRecorder()
  60. s.handleTransactionCommit(w, r)
  61. if w.Code != http.StatusBadRequest {
  62. t.Fatalf("commit status = %d, want 400; body %s", w.Code, w.Body.String())
  63. }
  64. var resp httpErrorBody
  65. if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
  66. t.Fatalf("decode: %v", err)
  67. }
  68. if resp.Error.Code != "23514" {
  69. t.Fatalf("code = %q, want 23514", resp.Error.Code)
  70. }
  71. constraint, _ := resp.Error.Details["constraint"].(string)
  72. if constraint == "" || !strings.Contains(resp.Error.Message, constraint) {
  73. t.Fatalf("details.constraint = %q, message = %q", constraint, resp.Error.Message)
  74. }
  75. }
  76. // The transaction endpoints only replace TRANSACTION_ERROR for constraint
  77. // violations; other commit failures keep the generic code.
  78. func TestConstraintViolationHTTPErrorIgnoresOtherErrors(t *testing.T) {
  79. if got := constraintViolationHTTPError(errors.New("boom")); got != nil {
  80. t.Fatalf("generic error mapped to %+v, want nil", got)
  81. }
  82. }
  83. func TestHTTPCheckViolationReturns23514(t *testing.T) {
  84. server := setupKVTestServer(t)
  85. queryHTTP(t, server, "CREATE TABLE t (id INTEGER PRIMARY KEY, age INTEGER, CONSTRAINT positive_age CHECK (age > 0))")
  86. body, _ := json.Marshal(QueryRequest{SQL: "INSERT INTO t (id, age) VALUES (1, -1)"})
  87. r := httptest.NewRequest(http.MethodPost, "/query", strings.NewReader(string(body)))
  88. w := httptest.NewRecorder()
  89. server.handleQuery(w, r)
  90. if w.Code != http.StatusBadRequest {
  91. t.Fatalf("status = %d, want 400; body %s", w.Code, w.Body.String())
  92. }
  93. var resp httpErrorBody
  94. if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
  95. t.Fatalf("decode: %v", err)
  96. }
  97. if resp.Error.Code != "23514" {
  98. t.Fatalf("code = %q, want 23514", resp.Error.Code)
  99. }
  100. constraint, _ := resp.Error.Details["constraint"].(string)
  101. if constraint != "positive_age" {
  102. t.Fatalf("details.constraint = %q, want positive_age", constraint)
  103. }
  104. }
  105. func TestSQLStateHTTPErrorMapping(t *testing.T) {
  106. tests := []struct {
  107. name string
  108. err error
  109. status int
  110. code string
  111. }{
  112. {"unique", fmt.Errorf("UNIQUE constraint failed: uniq_users_email"), http.StatusConflict, "23505"},
  113. {"not null", fmt.Errorf("NOT NULL constraint failed: t.v"), http.StatusBadRequest, "23502"},
  114. {"check", fmt.Errorf("CHECK constraint failed: positive_age"), http.StatusBadRequest, "23514"},
  115. {"typed check", &storage.CheckViolationError{Table: "t", Constraint: "positive_age"}, http.StatusBadRequest, "23514"},
  116. {"typed not null", &storage.NotNullViolationError{Table: "t", Column: "v"}, http.StatusBadRequest, "23502"},
  117. {"typed unique", &storage.UniqueViolationError{Constraint: "uq_email"}, http.StatusConflict, "23505"},
  118. {"typed primary key", &storage.PrimaryKeyViolationError{Table: "t", Key: "1"}, http.StatusConflict, "23505"},
  119. {"serialization", fmt.Errorf("commit: %w", storage.ErrSerialization), http.StatusConflict, "40001"},
  120. {"unsupported", fmt.Errorf("feature not supported: DEFAULT is not constant"), http.StatusBadRequest, "0A000"},
  121. {"other", errors.New("boom"), http.StatusInternalServerError, "EXECUTION_ERROR"},
  122. }
  123. for _, tt := range tests {
  124. t.Run(tt.name, func(t *testing.T) {
  125. got := sqlStateHTTPError(tt.err)
  126. if got.Status != tt.status || got.Code != tt.code {
  127. t.Fatalf("got status=%d code=%s, want status=%d code=%s", got.Status, got.Code, tt.status, tt.code)
  128. }
  129. })
  130. }
  131. }
  132. // The batch /execute endpoint commits its own transaction, so a constraint the
  133. // commit discovers must map to 23514 there too instead of TRANSACTION_ERROR.
  134. func TestHTTPExecuteCommitCheckViolationReturns23514(t *testing.T) {
  135. s := newTestDBServer(t)
  136. if w := postQuery(t, s, "CREATE TABLE t (id INTEGER PRIMARY KEY)"); w.Code != http.StatusOK {
  137. t.Fatalf("create table: %d %s", w.Code, w.Body.String())
  138. }
  139. w := postExecute(t, s, ExecuteRequest{
  140. Transaction: true,
  141. Statements: []QueryRequest{
  142. {SQL: "INSERT INTO t (id) VALUES (1)"},
  143. {SQL: "ALTER TABLE t ADD COLUMN qty INTEGER DEFAULT -1 CHECK (qty >= 0)"},
  144. },
  145. })
  146. if w.Code != http.StatusBadRequest {
  147. t.Fatalf("execute status = %d, want 400; body %s", w.Code, w.Body.String())
  148. }
  149. var resp httpErrorBody
  150. if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
  151. t.Fatalf("decode: %v", err)
  152. }
  153. if resp.Error.Code != "23514" {
  154. t.Fatalf("code = %q, want 23514", resp.Error.Code)
  155. }
  156. }