sqlstate_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. package httpserver
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "net/http/httptest"
  9. "strings"
  10. "testing"
  11. "github.com/danfragoso/pizzasql-next/pkg/pgerror"
  12. "github.com/danfragoso/pizzasql-next/pkg/storage"
  13. )
  14. type httpErrorBody struct {
  15. Error struct {
  16. Code string `json:"code"`
  17. Message string `json:"message"`
  18. Details map[string]interface{} `json:"details"`
  19. } `json:"error"`
  20. }
  21. func TestHTTPUniqueViolationReturns23505(t *testing.T) {
  22. server := setupKVTestServer(t)
  23. queryHTTP(t, server, "CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE)")
  24. queryHTTP(t, server, "INSERT INTO users (id, email) VALUES (1, 'a@x')")
  25. body, _ := json.Marshal(QueryRequest{SQL: "INSERT INTO users (id, email) VALUES (2, 'a@x')"})
  26. r := httptest.NewRequest(http.MethodPost, "/query", strings.NewReader(string(body)))
  27. w := httptest.NewRecorder()
  28. server.handleQuery(w, r)
  29. if w.Code != http.StatusConflict {
  30. t.Fatalf("status = %d, want 409; body %s", w.Code, w.Body.String())
  31. }
  32. var resp httpErrorBody
  33. if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
  34. t.Fatalf("decode: %v", err)
  35. }
  36. if resp.Error.Code != "23505" {
  37. t.Fatalf("code = %q, want 23505", resp.Error.Code)
  38. }
  39. constraint, _ := resp.Error.Details["constraint"].(string)
  40. if constraint == "" || !strings.Contains(resp.Error.Message, constraint) {
  41. t.Fatalf("details.constraint = %q, message = %q", constraint, resp.Error.Message)
  42. }
  43. }
  44. // A constraint the commit discovers must report its SQLSTATE instead of the
  45. // generic TRANSACTION_ERROR the transaction endpoints use for other failures.
  46. func TestHTTPCommitCheckViolationReturns23514(t *testing.T) {
  47. s := newTestDBServer(t)
  48. if w := postQuery(t, s, "CREATE TABLE t (id INTEGER PRIMARY KEY)"); w.Code != http.StatusOK {
  49. t.Fatalf("create table: %d %s", w.Code, w.Body.String())
  50. }
  51. txID := beginTransaction(t, s, "")
  52. if w := postTransactionQuery(t, s, txID, "INSERT INTO t (id) VALUES (1)"); w.Code != http.StatusOK {
  53. t.Fatalf("staged insert: %d %s", w.Code, w.Body.String())
  54. }
  55. // A second session publishes the constraint the staged row will violate.
  56. if w := postQuery(t, s, "ALTER TABLE t ADD COLUMN qty INTEGER DEFAULT -1 CHECK (qty >= 0)"); w.Code != http.StatusOK {
  57. t.Fatalf("add column: %d %s", w.Code, w.Body.String())
  58. }
  59. body, _ := json.Marshal(TransactionRequest{TransactionID: txID})
  60. r := httptest.NewRequest(http.MethodPost, "/transaction/commit", strings.NewReader(string(body)))
  61. w := httptest.NewRecorder()
  62. s.handleTransactionCommit(w, r)
  63. if w.Code != http.StatusBadRequest {
  64. t.Fatalf("commit status = %d, want 400; body %s", w.Code, w.Body.String())
  65. }
  66. var resp httpErrorBody
  67. if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
  68. t.Fatalf("decode: %v", err)
  69. }
  70. if resp.Error.Code != "23514" {
  71. t.Fatalf("code = %q, want 23514", resp.Error.Code)
  72. }
  73. constraint, _ := resp.Error.Details["constraint"].(string)
  74. if constraint == "" || !strings.Contains(resp.Error.Message, constraint) {
  75. t.Fatalf("details.constraint = %q, message = %q", constraint, resp.Error.Message)
  76. }
  77. }
  78. // The transaction endpoints only replace TRANSACTION_ERROR for constraint
  79. // violations; other commit failures keep the generic code.
  80. func TestConstraintViolationHTTPErrorIgnoresOtherErrors(t *testing.T) {
  81. if got := constraintViolationHTTPError(errors.New("boom")); got != nil {
  82. t.Fatalf("generic error mapped to %+v, want nil", got)
  83. }
  84. }
  85. func TestHTTPCheckViolationReturns23514(t *testing.T) {
  86. server := setupKVTestServer(t)
  87. queryHTTP(t, server, "CREATE TABLE t (id INTEGER PRIMARY KEY, age INTEGER, CONSTRAINT positive_age CHECK (age > 0))")
  88. body, _ := json.Marshal(QueryRequest{SQL: "INSERT INTO t (id, age) VALUES (1, -1)"})
  89. r := httptest.NewRequest(http.MethodPost, "/query", strings.NewReader(string(body)))
  90. w := httptest.NewRecorder()
  91. server.handleQuery(w, r)
  92. if w.Code != http.StatusBadRequest {
  93. t.Fatalf("status = %d, want 400; body %s", w.Code, w.Body.String())
  94. }
  95. var resp httpErrorBody
  96. if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
  97. t.Fatalf("decode: %v", err)
  98. }
  99. if resp.Error.Code != "23514" {
  100. t.Fatalf("code = %q, want 23514", resp.Error.Code)
  101. }
  102. constraint, _ := resp.Error.Details["constraint"].(string)
  103. if constraint != "positive_age" {
  104. t.Fatalf("details.constraint = %q, want positive_age", constraint)
  105. }
  106. }
  107. func TestSQLStateHTTPErrorMapping(t *testing.T) {
  108. tests := []struct {
  109. name string
  110. err error
  111. status int
  112. code string
  113. }{
  114. {"unique", fmt.Errorf("UNIQUE constraint failed: uniq_users_email"), http.StatusConflict, "23505"},
  115. {"foreign key", fmt.Errorf("FOREIGN KEY constraint failed: parent_id -> parent"), http.StatusConflict, "23503"},
  116. {"typed foreign key", &storage.ForeignKeyViolationError{Table: "child", Constraint: "parent_id -> parent"}, http.StatusConflict, "23503"},
  117. {"not null", fmt.Errorf("NOT NULL constraint failed: t.v"), http.StatusBadRequest, "23502"},
  118. {"check", fmt.Errorf("CHECK constraint failed: positive_age"), http.StatusBadRequest, "23514"},
  119. {"typed check", &storage.CheckViolationError{Table: "t", Constraint: "positive_age"}, http.StatusBadRequest, "23514"},
  120. {"typed not null", &storage.NotNullViolationError{Table: "t", Column: "v"}, http.StatusBadRequest, "23502"},
  121. {"typed unique", &storage.UniqueViolationError{Constraint: "uq_email"}, http.StatusConflict, "23505"},
  122. {"typed primary key", &storage.PrimaryKeyViolationError{Table: "t", Key: "1"}, http.StatusConflict, "23505"},
  123. {"serialization", fmt.Errorf("commit: %w", storage.ErrSerialization), http.StatusConflict, "40001"},
  124. {"unsupported", fmt.Errorf("feature not supported: DEFAULT is not constant"), http.StatusBadRequest, "0A000"},
  125. {"undefined table", pgerror.UndefinedTable("relation %q does not exist", "missing"), http.StatusNotFound, "42P01"},
  126. {"other", errors.New("boom"), http.StatusInternalServerError, "EXECUTION_ERROR"},
  127. }
  128. for _, tt := range tests {
  129. t.Run(tt.name, func(t *testing.T) {
  130. got := sqlStateHTTPError(tt.err)
  131. if got.Status != tt.status || got.Code != tt.code {
  132. t.Fatalf("got status=%d code=%s, want status=%d code=%s", got.Status, got.Code, tt.status, tt.code)
  133. }
  134. })
  135. }
  136. }
  137. // The batch /execute endpoint commits its own transaction, so a constraint the
  138. // commit discovers must map to 23514 there too instead of TRANSACTION_ERROR.
  139. func TestHTTPExecuteCommitCheckViolationReturns23514(t *testing.T) {
  140. s := newTestDBServer(t)
  141. if w := postQuery(t, s, "CREATE TABLE t (id INTEGER PRIMARY KEY)"); w.Code != http.StatusOK {
  142. t.Fatalf("create table: %d %s", w.Code, w.Body.String())
  143. }
  144. w := postExecute(t, s, ExecuteRequest{
  145. Transaction: true,
  146. Statements: []QueryRequest{
  147. {SQL: "INSERT INTO t (id) VALUES (1)"},
  148. {SQL: "ALTER TABLE t ADD COLUMN qty INTEGER DEFAULT -1 CHECK (qty >= 0)"},
  149. },
  150. })
  151. if w.Code != http.StatusBadRequest {
  152. t.Fatalf("execute status = %d, want 400; body %s", w.Code, w.Body.String())
  153. }
  154. var resp httpErrorBody
  155. if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
  156. t.Fatalf("decode: %v", err)
  157. }
  158. if resp.Error.Code != "23514" {
  159. t.Fatalf("code = %q, want 23514", resp.Error.Code)
  160. }
  161. }
  162. // A dangling foreign key reports 23503 through the query endpoint, with the
  163. // constraint label in details.
  164. func TestHTTPForeignKeyViolationReturns23503(t *testing.T) {
  165. server := setupKVTestServer(t)
  166. queryHTTP(t, server, "CREATE TABLE parent (id INTEGER PRIMARY KEY)")
  167. queryHTTP(t, server, "CREATE TABLE child (id INTEGER PRIMARY KEY, parent_id INTEGER, CONSTRAINT child_parent FOREIGN KEY (parent_id) REFERENCES parent(id))")
  168. body, _ := json.Marshal(QueryRequest{SQL: "INSERT INTO child (id, parent_id) VALUES (1, 99)"})
  169. r := httptest.NewRequest(http.MethodPost, "/query", strings.NewReader(string(body)))
  170. w := httptest.NewRecorder()
  171. server.handleQuery(w, r)
  172. if w.Code != http.StatusConflict {
  173. t.Fatalf("status = %d, want 409; body %s", w.Code, w.Body.String())
  174. }
  175. var resp httpErrorBody
  176. if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
  177. t.Fatalf("decode: %v", err)
  178. }
  179. if resp.Error.Code != "23503" {
  180. t.Fatalf("code = %q, want 23503", resp.Error.Code)
  181. }
  182. if constraint, _ := resp.Error.Details["constraint"].(string); constraint != "child_parent" {
  183. t.Fatalf("details.constraint = %q, want child_parent", constraint)
  184. }
  185. }
  186. // Array containment and set-returning-function column aliases run through the
  187. // HTTP surface with the same values and SQLSTATEs as the wire protocol.
  188. func TestHTTPArrayContainmentAndSRFAlias(t *testing.T) {
  189. server := setupKVTestServer(t)
  190. queryHTTP(t, server, `CREATE TABLE items (id INTEGER PRIMARY KEY, nums INTEGER[])`)
  191. queryHTTP(t, server, `INSERT INTO items (id, nums) VALUES (1, '{1,2,NULL}'), (2, '{3}')`)
  192. resp := queryHTTP(t, server, `SELECT id FROM items WHERE nums @> ARRAY[2]`)
  193. if len(resp.Rows) != 1 || resp.Rows[0][0].(float64) != 1 {
  194. t.Fatalf("array containment rows = %#v", resp.Rows)
  195. }
  196. resp = queryHTTP(t, server, `SELECT id FROM items WHERE nums @> ARRAY[NULL]::INTEGER[]`)
  197. if len(resp.Rows) != 1 || resp.Rows[0][0].(float64) != 1 {
  198. t.Fatalf("NULL element containment rows = %#v", resp.Rows)
  199. }
  200. resp = queryHTTP(t, server, `SELECT n FROM unnest(ARRAY[5,6]) AS u(n) WHERE n = 6`)
  201. if len(resp.Columns) != 1 || resp.Columns[0].Name != "n" || len(resp.Rows) != 1 || resp.Rows[0][0].(float64) != 6 {
  202. t.Fatalf("alias list response = columns %#v rows %#v", resp.Columns, resp.Rows)
  203. }
  204. post := func(sql string) *httptest.ResponseRecorder {
  205. body, _ := json.Marshal(QueryRequest{SQL: sql})
  206. r := httptest.NewRequest(http.MethodPost, "/query", bytes.NewReader(body))
  207. w := httptest.NewRecorder()
  208. server.handleQuery(w, r)
  209. return w
  210. }
  211. for _, tc := range []struct {
  212. sql string
  213. code string
  214. }{
  215. {`SELECT * FROM unnest(ARRAY[1]) AS u(a, b)`, pgerror.CodeInvalidColumnReference},
  216. {`SELECT * FROM items WHERE nums @> 1`, pgerror.CodeDatatypeMismatch},
  217. } {
  218. w := post(tc.sql)
  219. if w.Code != http.StatusBadRequest {
  220. t.Fatalf("%s status = %d, want 400; body %s", tc.sql, w.Code, w.Body.String())
  221. }
  222. var resp httpErrorBody
  223. if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
  224. t.Fatalf("decode: %v", err)
  225. }
  226. if resp.Error.Code != tc.code {
  227. t.Fatalf("%s code = %q, want %s", tc.sql, resp.Error.Code, tc.code)
  228. }
  229. }
  230. }