2
0

features_test.go 8.8 KB

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