features_test.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. package pgserver
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/binary"
  6. "net"
  7. "strings"
  8. "testing"
  9. "github.com/danfragoso/pizzasql-next/pkg/executor"
  10. "github.com/danfragoso/pizzasql-next/pkg/storage"
  11. "github.com/danfragoso/pizzasql-next/pkg/testkv"
  12. )
  13. // newDataConnection builds a connection with a real executor backed by testkv so
  14. // simple-query behavior can be asserted end to end.
  15. func newDataConnection(t *testing.T) (*Connection, net.Conn) {
  16. t.Helper()
  17. kv := testkv.New(t)
  18. pool := kv.Pool(4)
  19. t.Cleanup(func() { pool.Close() })
  20. schema := storage.NewSchemaManager(pool, "pg_features")
  21. table := storage.NewTableManager(pool, schema, "pg_features")
  22. return newDataConnectionFor(t, schema, table)
  23. }
  24. // newDataConnectionFor wires a wire connection to an existing storage engine, so
  25. // a test can drive two independent sessions over one shared store.
  26. func newDataConnectionFor(t *testing.T, schema *storage.SchemaManager, table *storage.TableManager) (*Connection, net.Conn) {
  27. t.Helper()
  28. server, client := net.Pipe()
  29. t.Cleanup(func() {
  30. server.Close()
  31. client.Close()
  32. })
  33. exec := executor.New(schema, table)
  34. exec.SyncCatalog()
  35. c := &Connection{
  36. conn: server,
  37. reader: bufio.NewReader(server),
  38. writer: bufio.NewWriter(server),
  39. params: map[string]string{"user": "tester"},
  40. statements: make(map[string]*preparedStatement),
  41. portals: make(map[string]*portal),
  42. txStatus: TxStatusIdle,
  43. quiet: true,
  44. executor: exec,
  45. schema: schema,
  46. }
  47. return c, client
  48. }
  49. // dataRowValues decodes a DataRow message into its text values.
  50. func dataRowValues(t *testing.T, msg *Message) []string {
  51. t.Helper()
  52. if msg.Type != MsgDataRow {
  53. t.Fatalf("message type = %c, want DataRow", msg.Type)
  54. }
  55. data := msg.Data
  56. if len(data) < 2 {
  57. t.Fatal("short DataRow")
  58. }
  59. count := int(binary.BigEndian.Uint16(data[:2]))
  60. pos := 2
  61. values := make([]string, 0, count)
  62. for i := 0; i < count; i++ {
  63. if pos+4 > len(data) {
  64. t.Fatal("short DataRow field length")
  65. }
  66. l := int32(binary.BigEndian.Uint32(data[pos : pos+4]))
  67. pos += 4
  68. if l == -1 {
  69. values = append(values, "<null>")
  70. continue
  71. }
  72. values = append(values, string(data[pos:pos+int(l)]))
  73. pos += int(l)
  74. }
  75. return values
  76. }
  77. // A durable implicit commit may report its LSN between result completion and
  78. // ReadyForQuery. Keep result-shape assertions independent of status updates.
  79. func resultMessages(messages []*Message) []*Message {
  80. var result []*Message
  81. for _, message := range messages {
  82. if message.Type != MsgParameterStatus {
  83. result = append(result, message)
  84. }
  85. }
  86. return result
  87. }
  88. // commandTag extracts the NUL-terminated tag from a CommandComplete message.
  89. func commandTag(t *testing.T, msg *Message) string {
  90. t.Helper()
  91. if msg.Type != MsgCommandComplete {
  92. t.Fatalf("message type = %c, want CommandComplete", msg.Type)
  93. }
  94. return string(bytes.TrimRight(msg.Data, "\x00"))
  95. }
  96. func TestSimpleQueryInsertReturning(t *testing.T) {
  97. c, client := newDataConnection(t)
  98. runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte("CREATE TABLE t (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)"), 0)})
  99. msgs := resultMessages(runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte("INSERT INTO t (name) VALUES ('alice') RETURNING id, name"), 0)}))
  100. if len(msgs) != 4 {
  101. t.Fatalf("got %d messages, want RowDescription+DataRow+CommandComplete+ReadyForQuery: %v", len(msgs), msgs)
  102. }
  103. if msgs[0].Type != MsgRowDescription {
  104. t.Fatalf("first message = %c, want RowDescription", msgs[0].Type)
  105. }
  106. values := dataRowValues(t, msgs[1])
  107. if len(values) != 2 || values[0] != "1" || values[1] != "alice" {
  108. t.Fatalf("returning row = %v", values)
  109. }
  110. if tag := commandTag(t, msgs[2]); tag != "INSERT 0 1" {
  111. t.Fatalf("command tag = %q, want INSERT 0 1", tag)
  112. }
  113. }
  114. func TestSimpleQueryByteaTextWire(t *testing.T) {
  115. c, client := newDataConnection(t)
  116. runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte("CREATE TABLE b (id INTEGER PRIMARY KEY, data BLOB)"), 0)})
  117. runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte("INSERT INTO b (id, data) VALUES (1, X'00FF10')"), 0)})
  118. msgs := runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte("SELECT data FROM b WHERE id = 1"), 0)})
  119. values := dataRowValues(t, msgs[1])
  120. if len(values) != 1 || values[0] != `\x00ff10` {
  121. t.Fatalf("bytea wire value = %v, want \\x00ff10", values)
  122. }
  123. }
  124. func TestBlobValueOverridesTextAffinityWireType(t *testing.T) {
  125. result := executor.NewResult("SELECT")
  126. result.AddColumnWithType("settings", "VARCHAR")
  127. result.AddRow([]byte(`{"collect":1}`))
  128. types := wireColumnTypes(result)
  129. if len(types) != 1 || types[0] != "BLOB" {
  130. t.Fatalf("wire types = %v, want [BLOB]", types)
  131. }
  132. if result.ColumnTypes[0] != "VARCHAR" {
  133. t.Fatalf("wire type inference mutated result metadata: %v", result.ColumnTypes)
  134. }
  135. }
  136. func TestCommandTagSelectAndUpdate(t *testing.T) {
  137. c, client := newDataConnection(t)
  138. runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte("CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)"), 0)})
  139. runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte("INSERT INTO t VALUES (1, 'a')"), 0)})
  140. msgs := runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte("SELECT * FROM t"), 0)})
  141. if tag := commandTag(t, msgs[len(msgs)-2]); tag != "SELECT 1" {
  142. t.Fatalf("select tag = %q", tag)
  143. }
  144. msgs = resultMessages(runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte("UPDATE t SET v='b' RETURNING id"), 0)}))
  145. if msgs[0].Type != MsgRowDescription {
  146. t.Fatalf("update returning first message = %c", msgs[0].Type)
  147. }
  148. if tag := commandTag(t, msgs[len(msgs)-2]); tag != "UPDATE 1" {
  149. t.Fatalf("update tag = %q", tag)
  150. }
  151. }
  152. func TestGetCommandTagSelectUsesRowCount(t *testing.T) {
  153. c := &Connection{txStatus: TxStatusIdle}
  154. res := executor.NewResult("SELECT")
  155. res.AddRow(1)
  156. res.AddRow(2)
  157. if tag := c.getCommandTag(parseStmt(t, "SELECT 1"), res); tag != "SELECT 2" {
  158. t.Fatalf("tag = %q, want SELECT 2", tag)
  159. }
  160. }
  161. // errorMessage extracts the human-readable message from an ErrorResponse.
  162. func errorMessage(msg *Message) string {
  163. if msg == nil || msg.Type != MsgErrorResponse {
  164. return ""
  165. }
  166. data := msg.Data
  167. for i := 0; i < len(data); {
  168. if data[i] == 0 {
  169. break
  170. }
  171. field := data[i]
  172. i++
  173. end := bytes.IndexByte(data[i:], 0)
  174. if end < 0 {
  175. break
  176. }
  177. value := string(data[i : i+end])
  178. if field == ErrorFieldMessage {
  179. return value
  180. }
  181. i += end + 1
  182. }
  183. return ""
  184. }
  185. func TestSimpleQueryUniqueViolationErrorCode(t *testing.T) {
  186. c, client := newDataConnection(t)
  187. runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte("CREATE TABLE t (id INTEGER PRIMARY KEY, email TEXT UNIQUE)"), 0)})
  188. runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte("INSERT INTO t VALUES (1, 'a@x')"), 0)})
  189. msgs := runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte("INSERT INTO t VALUES (2, 'a@x')"), 0)})
  190. if len(msgs) != 2 {
  191. t.Fatalf("got %d messages, want ErrorResponse+ReadyForQuery", len(msgs))
  192. }
  193. if code := errorCode(msgs[0]); code != ErrCodeUniqueViolation {
  194. t.Fatalf("error code = %q, want %q", code, ErrCodeUniqueViolation)
  195. }
  196. if message := errorMessage(msgs[0]); !strings.Contains(message, "uniq_t_email") {
  197. t.Fatalf("error message = %q, want constraint uniq_t_email", message)
  198. }
  199. }
  200. func TestExtendedQueryUniqueViolationErrorCode(t *testing.T) {
  201. c, client := newDataConnection(t)
  202. runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte("CREATE TABLE t (id INTEGER PRIMARY KEY, email TEXT UNIQUE)"), 0)})
  203. runQuery(t, c, client, &Message{Type: MsgQuery, Data: append([]byte("INSERT INTO t VALUES (1, 'a@x')"), 0)})
  204. parse := NewMessageBuilder()
  205. parse.WriteString("")
  206. parse.WriteString("INSERT INTO t VALUES (2, 'a@x')")
  207. parse.WriteInt16(0)
  208. bind := NewMessageBuilder()
  209. bind.WriteString("")
  210. bind.WriteString("")
  211. bind.WriteInt16(0) // parameter format codes
  212. bind.WriteInt16(0) // parameter values
  213. bind.WriteInt16(0) // result format codes
  214. execute := NewMessageBuilder()
  215. execute.WriteString("")
  216. execute.WriteInt32(0)
  217. done := make(chan error, 1)
  218. go func() {
  219. if err := c.handleParse(&Message{Type: MsgParse, Data: parse.Bytes()}); err != nil {
  220. done <- err
  221. return
  222. }
  223. if err := c.handleBind(&Message{Type: MsgBind, Data: bind.Bytes()}); err != nil {
  224. done <- err
  225. return
  226. }
  227. done <- c.handleExecute(&Message{Type: MsgExecute, Data: execute.Bytes()})
  228. }()
  229. reader := bufio.NewReader(client)
  230. var errMsg *Message
  231. for errMsg == nil {
  232. msg, err := ReadMessage(reader)
  233. if err != nil {
  234. t.Fatalf("read response: %v", err)
  235. }
  236. if msg.Type == MsgErrorResponse {
  237. errMsg = msg
  238. }
  239. }
  240. if err := <-done; err != nil {
  241. t.Fatalf("extended query: %v", err)
  242. }
  243. if code := errorCode(errMsg); code != ErrCodeUniqueViolation {
  244. t.Fatalf("error code = %q, want %q", code, ErrCodeUniqueViolation)
  245. }
  246. if message := errorMessage(errMsg); !strings.Contains(message, "uniq_t_email") {
  247. t.Fatalf("error message = %q, want constraint uniq_t_email", message)
  248. }
  249. }