compat_suite_test.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. package pgserver
  2. // Compatibility suite for the pChat-style workload: DDL, upsert idempotency,
  3. // constraints, pagination, parameters, and error codes. It runs only when
  4. // PIZZASQL_COMPAT=1 so the regular unit suite stays fast; `make compat` enables
  5. // it and writes a JSON report.
  6. //
  7. // The suite distinguishes:
  8. // - pass: the build behaves as documented
  9. // - missing: a documented capability is absent from this build (for example a
  10. // rejection introduced by a newer release)
  11. // - fail: behavior contradicts the documented contract
  12. //
  13. // PIZZASQL_COMPAT_STRICT=1 turns "missing" into a failure, which is what a
  14. // release gate should use. The compatibility document is pkg/capabilities.
  15. import (
  16. "encoding/json"
  17. "os"
  18. "strconv"
  19. "testing"
  20. )
  21. func rowValue(rows [][]string, index int) string {
  22. if len(rows) <= index || len(rows[index]) == 0 {
  23. return ""
  24. }
  25. return rows[index][0]
  26. }
  27. type compatResult struct {
  28. Name string `json:"name"`
  29. Status string `json:"status"` // pass, missing, fail
  30. Detail string `json:"detail,omitempty"`
  31. }
  32. type compatReport struct {
  33. Engine string `json:"engine"`
  34. Results []compatResult `json:"results"`
  35. }
  36. func TestCompatibilitySuite(t *testing.T) {
  37. if os.Getenv("PIZZASQL_COMPAT") != "1" {
  38. t.Skip("set PIZZASQL_COMPAT=1 (or run make compat) to run the compatibility suite")
  39. }
  40. strict := os.Getenv("PIZZASQL_COMPAT_STRICT") == "1"
  41. c, client := newDataConnection(t)
  42. report := compatReport{Engine: "pizzasql"}
  43. record := func(name, status, detail string) {
  44. report.Results = append(report.Results, compatResult{Name: name, Status: status, Detail: detail})
  45. }
  46. // exec runs a statement and returns the SQLSTATE code ("" on success) and
  47. // decoded rows.
  48. exec := func(sql string) (string, [][]string) {
  49. msgs := runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte(sql), 0)})
  50. if len(msgs) == 0 {
  51. return "", nil
  52. }
  53. if msgs[0].Type == MsgErrorResponse {
  54. return errorCode(msgs[0]), nil
  55. }
  56. var rows [][]string
  57. for _, msg := range msgs[1:] {
  58. if msg.Type != MsgDataRow {
  59. continue
  60. }
  61. rows = append(rows, dataRowValues(t, msg))
  62. }
  63. return "", rows
  64. }
  65. expectOK := func(name, sql string) {
  66. if code, _ := exec(sql); code != "" {
  67. record(name, "fail", "unexpected SQLSTATE "+code)
  68. return
  69. }
  70. record(name, "pass", "")
  71. }
  72. expectCode := func(name, sql, want string) {
  73. code, _ := exec(sql)
  74. switch code {
  75. case want:
  76. record(name, "pass", "")
  77. case "":
  78. record(name, "missing", "statement succeeded; this build does not enforce "+want)
  79. default:
  80. record(name, "missing", "got SQLSTATE "+code+", want "+want)
  81. }
  82. }
  83. expectRows := func(name, sql string, want ...string) {
  84. code, rows := exec(sql)
  85. if code != "" {
  86. record(name, "fail", "unexpected SQLSTATE "+code)
  87. return
  88. }
  89. if len(rows) != 1 || len(rows[0]) != len(want) {
  90. record(name, "fail", "unexpected rows")
  91. return
  92. }
  93. for i := range want {
  94. if rows[0][i] != want[i] {
  95. record(name, "fail", "row "+rows[0][i]+" != "+want[i])
  96. return
  97. }
  98. }
  99. record(name, "pass", "")
  100. }
  101. expectOK("ddl.create_table", `CREATE TABLE accounts (
  102. id INTEGER PRIMARY KEY,
  103. email TEXT NOT NULL UNIQUE,
  104. plan TEXT NOT NULL DEFAULT 'free',
  105. seats INTEGER NOT NULL DEFAULT 1
  106. )`)
  107. expectOK("dml.insert", `INSERT INTO accounts (id, email, plan, seats) VALUES (1, 'a@x', 'pro', 3)`)
  108. expectRows("dml.select_constant_default", `SELECT plan, seats FROM accounts WHERE id = 1`, "pro", "3")
  109. expectOK("upsert.first", `INSERT INTO accounts (id, email, plan) VALUES (2, 'b@x', 'free') ON CONFLICT(id) DO UPDATE SET plan = excluded.plan`)
  110. expectOK("upsert.idempotent", `INSERT INTO accounts (id, email, plan) VALUES (2, 'b@x', 'pro') ON CONFLICT(id) DO UPDATE SET plan = excluded.plan`)
  111. expectRows("upsert.result", `SELECT plan FROM accounts WHERE id = 2`, "pro")
  112. expectCode("constraints.unique_23505", `INSERT INTO accounts (id, email) VALUES (3, 'a@x')`, "23505")
  113. expectCode("ddl.composite_pk_0A000", `CREATE TABLE bad_pk (a INTEGER, b INTEGER, PRIMARY KEY (a, b))`, "0A000")
  114. expectCode("ddl.nonconstant_default_0A000", `CREATE TABLE bad_default (id INTEGER PRIMARY KEY, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)`, "0A000")
  115. expectCode("locking.for_update_0A000", `SELECT * FROM accounts FOR UPDATE`, "0A000")
  116. expectCode("arrays.any_0A000", `SELECT * FROM accounts WHERE id = ANY('{1,2}')`, "0A000")
  117. // Documented current limitation: CHECK and FOREIGN KEY are parsed but not
  118. // enforced. A release that starts rejecting them will report "missing"
  119. // here and the capability document must be updated.
  120. expectOK("limitations.check_not_enforced", `CREATE TABLE checked (n INTEGER CHECK (n > 0))`)
  121. expectOK("limitations.check_insert_violation", `INSERT INTO checked (n) VALUES (-1)`)
  122. expectOK("limitations.foreign_key_not_enforced", `CREATE TABLE child (id INTEGER PRIMARY KEY, parent_id INTEGER, FOREIGN KEY (parent_id) REFERENCES accounts(id))`)
  123. expectOK("limitations.orphan_insert", `INSERT INTO child (id, parent_id) VALUES (1, 999)`)
  124. expectCode("errors.syntax_42601", `SELEC 1`, "42601")
  125. // Explicit transactions buffer writes and validate unique indexes at
  126. // COMMIT, so the duplicate insert itself succeeds and the commit fails.
  127. expectOK("tx.begin", `BEGIN`)
  128. expectOK("tx.buffer_duplicate", `INSERT INTO accounts (id, email) VALUES (3, 'a@x')`)
  129. expectCode("tx.commit_unique_23505", `COMMIT`, "23505")
  130. // A failed COMMIT has already rolled back; the session must be usable
  131. // again instead of being stuck in the failed-transaction state.
  132. expectRows("tx.after_failed_commit_idle", `SELECT 1`, "1")
  133. expectOK("tx.begin_after_failed_commit", `BEGIN`)
  134. expectOK("tx.rollback", `ROLLBACK`)
  135. expectOK("pagination.seed", `INSERT INTO accounts (id, email) VALUES (10, 'p10@x'), (11, 'p11@x'), (12, 'p12@x')`)
  136. code, rows := exec(`SELECT _rowid_ FROM accounts WHERE _rowid_ > 1 ORDER BY _rowid_ LIMIT 2`)
  137. first, firstErr := strconv.ParseInt(rowValue(rows, 0), 10, 64)
  138. second, secondErr := strconv.ParseInt(rowValue(rows, 1), 10, 64)
  139. switch {
  140. case code != "":
  141. record("pagination.rowid", "fail", "unexpected SQLSTATE "+code)
  142. case len(rows) == 2 && firstErr == nil && secondErr == nil && first < second:
  143. record("pagination.rowid", "pass", "")
  144. default:
  145. record("pagination.rowid", "fail", "cursor did not advance")
  146. }
  147. failures, missing := 0, 0
  148. for _, result := range report.Results {
  149. switch result.Status {
  150. case "fail":
  151. failures++
  152. t.Errorf("%s: %s", result.Name, result.Detail)
  153. case "missing":
  154. missing++
  155. t.Logf("%s: %s", result.Name, result.Detail)
  156. }
  157. }
  158. if path := os.Getenv("PIZZASQL_COMPAT_REPORT"); path != "" {
  159. body, err := json.MarshalIndent(report, "", " ")
  160. if err != nil {
  161. t.Fatalf("marshal report: %v", err)
  162. }
  163. if err := os.WriteFile(path, body, 0o644); err != nil {
  164. t.Fatalf("write report: %v", err)
  165. }
  166. }
  167. if failures > 0 || (strict && missing > 0) {
  168. t.Fatalf("compatibility failures=%d missing=%d (strict=%v)", failures, missing, strict)
  169. }
  170. }