sqlstate_test.go 8.1 KB

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