2
0

connection.go 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742
  1. package pgserver
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/binary"
  6. "encoding/hex"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "log"
  11. "net"
  12. "os"
  13. "regexp"
  14. "sort"
  15. "strconv"
  16. "strings"
  17. "sync/atomic"
  18. "github.com/danfragoso/pizzasql-next/pkg/analyzer"
  19. "github.com/danfragoso/pizzasql-next/pkg/executor"
  20. "github.com/danfragoso/pizzasql-next/pkg/lexer"
  21. "github.com/danfragoso/pizzasql-next/pkg/parser"
  22. "github.com/danfragoso/pizzasql-next/pkg/pgerror"
  23. "github.com/danfragoso/pizzasql-next/pkg/storage"
  24. "github.com/danfragoso/pizzasql-next/pkg/version"
  25. )
  26. // Connection represents a client connection
  27. type Connection struct {
  28. conn net.Conn
  29. reader *bufio.Reader
  30. writer *bufio.Writer
  31. executor *executor.Executor
  32. schema *storage.SchemaManager
  33. table *storage.TableManager
  34. dbManager *storage.DatabaseManager
  35. database string
  36. params map[string]string
  37. txStatus byte
  38. quiet bool // Disable query logging
  39. statements map[string]*preparedStatement
  40. portals map[string]*portal
  41. extendedFailed bool
  42. backendPID int32
  43. // extendedCycle is true between Parse/Bind/Execute/Describe/Close and the
  44. // next Sync. Notifications are not interleaved into an extended-protocol
  45. // sequence; they are held until Sync.
  46. extendedCycle bool
  47. // catalogFallback serves catalog emulation before the executor exists, when
  48. // a connection has managers but has not completed startup.
  49. catalogFallback *storage.Session
  50. }
  51. // backendPIDSeq gives each connection a distinct synthetic backend PID. It is
  52. // seeded with the process ID so NotificationResponse frames look plausible and
  53. // do not collide across server processes.
  54. var backendPIDSeq atomic.Int32
  55. func nextBackendPID() int32 {
  56. return int32(os.Getpid()) + backendPIDSeq.Add(1)
  57. }
  58. type preparedStatement struct {
  59. query string
  60. paramOIDs []int32
  61. }
  62. type portal struct {
  63. query string
  64. executed bool
  65. }
  66. // NewConnection creates a new connection handler
  67. func NewConnection(conn net.Conn, dbManager *storage.DatabaseManager, quiet bool) *Connection {
  68. return &Connection{
  69. conn: conn,
  70. reader: bufio.NewReader(conn),
  71. writer: bufio.NewWriter(conn),
  72. dbManager: dbManager,
  73. params: make(map[string]string),
  74. statements: make(map[string]*preparedStatement),
  75. portals: make(map[string]*portal),
  76. txStatus: TxStatusIdle,
  77. quiet: quiet,
  78. backendPID: nextBackendPID(),
  79. }
  80. }
  81. // Handle processes the connection
  82. func (c *Connection) Handle() error {
  83. defer func() {
  84. if c.executor != nil {
  85. if err := c.executor.Close(); err != nil && !c.quiet {
  86. log.Printf("failed to close session: %v", err)
  87. }
  88. }
  89. c.conn.Close()
  90. }()
  91. // First, check for SSL request (sent before startup message)
  92. // SSL request is 8 bytes: length(4) + code(4) where code = 80877103
  93. firstBytes := make([]byte, 8)
  94. n, err := io.ReadFull(c.reader, firstBytes)
  95. if err != nil {
  96. return fmt.Errorf("failed to read initial bytes: %w", err)
  97. }
  98. // Check if it's an SSL request (code 80877103 = 0x04D2162F)
  99. if n == 8 {
  100. length := binary.BigEndian.Uint32(firstBytes[0:4])
  101. code := binary.BigEndian.Uint32(firstBytes[4:8])
  102. if length == 8 && code == 80877103 {
  103. // SSL request - we don't support SSL, send 'N'
  104. if !c.quiet {
  105. log.Printf("Client requested SSL, sending rejection")
  106. }
  107. if _, err := c.conn.Write([]byte{'N'}); err != nil {
  108. return fmt.Errorf("failed to send SSL rejection: %w", err)
  109. }
  110. // Now read the actual startup message
  111. } else {
  112. // Not SSL request, this is part of startup message
  113. // We need to prepend these bytes back for ReadStartupMessage
  114. // Create a multi-reader that first reads our buffered bytes, then continues with the reader
  115. c.reader = bufio.NewReader(io.MultiReader(bytes.NewReader(firstBytes), c.reader))
  116. }
  117. }
  118. // Read startup message
  119. if !c.quiet {
  120. log.Printf("Reading startup message...")
  121. }
  122. params, err := ReadStartupMessage(c.reader)
  123. if err != nil {
  124. return fmt.Errorf("failed to read startup message: %w", err)
  125. }
  126. c.params = params
  127. if !c.quiet {
  128. log.Printf("Startup params: %+v", params)
  129. }
  130. // Get database name from params (default to "pizzasql")
  131. dbName := params["database"]
  132. if dbName == "" {
  133. dbName = "pizzasql"
  134. }
  135. c.database = dbName
  136. if !c.quiet {
  137. log.Printf("New connection: user=%s database=%s", params["user"], dbName)
  138. }
  139. // Initialize database
  140. if err := c.initDatabase(dbName); err != nil {
  141. c.sendError("FATAL", ErrCodeConnectionFailure, fmt.Sprintf("Failed to initialize database: %v", err))
  142. return err
  143. }
  144. // Send authentication OK (no auth for now)
  145. if err := c.sendAuthenticationOk(); err != nil {
  146. return err
  147. }
  148. // Send parameter status messages
  149. if err := c.sendParameterStatus("server_version", version.PostgreSQLCompatVersion+" (PizzaSQL)"); err != nil {
  150. return err
  151. }
  152. // Build identity is a separate, custom ParameterStatus so the PostgreSQL
  153. // compatibility string above stays stable for version-sniffing drivers.
  154. if err := c.sendParameterStatus("pizzasql.version", version.String()); err != nil {
  155. return err
  156. }
  157. if err := c.sendParameterStatus("pizzasql.commit", version.Commit); err != nil {
  158. return err
  159. }
  160. if err := c.sendParameterStatus("pizzasql.proxy_errors", "1"); err != nil {
  161. return err
  162. }
  163. if err := c.sendParameterStatus("server_encoding", "UTF8"); err != nil {
  164. return err
  165. }
  166. if err := c.sendParameterStatus("client_encoding", "UTF8"); err != nil {
  167. return err
  168. }
  169. if err := c.sendParameterStatus("DateStyle", "ISO, MDY"); err != nil {
  170. return err
  171. }
  172. if err := c.sendParameterStatus("TimeZone", "UTC"); err != nil {
  173. return err
  174. }
  175. // Send backend key data (for cancellation - we don't implement this yet)
  176. if err := c.sendBackendKeyData(c.backendPID, 67890); err != nil {
  177. return err
  178. }
  179. // Send ready for query
  180. if err := c.sendReadyForQuery(); err != nil {
  181. return err
  182. }
  183. // Read messages on a separate goroutine so an idle listener can receive
  184. // asynchronous NotificationResponse frames while blocked waiting for input.
  185. // Only this goroutine writes to c.writer, which keeps frame order intact.
  186. type readResult struct {
  187. msg *Message
  188. err error
  189. }
  190. inbox := make(chan readResult, 16)
  191. done := make(chan struct{})
  192. defer close(done)
  193. go func() {
  194. for {
  195. msg, err := ReadMessage(c.reader)
  196. select {
  197. case inbox <- readResult{msg: msg, err: err}:
  198. case <-done:
  199. return
  200. }
  201. if err != nil {
  202. return
  203. }
  204. }
  205. }()
  206. notifications := c.executor.NotificationChannel()
  207. overflow := c.executor.NotificationOverflow()
  208. for {
  209. // Do not interleave notifications into an extended-protocol cycle. The
  210. // channel is disabled until Sync closes the cycle.
  211. var notifyCh <-chan storage.Notification
  212. if !c.extendedCycle {
  213. notifyCh = notifications
  214. }
  215. select {
  216. case res := <-inbox:
  217. if res.err != nil {
  218. if res.err == io.EOF {
  219. log.Printf("Connection closed by client")
  220. return nil
  221. }
  222. return fmt.Errorf("failed to read message: %w", res.err)
  223. }
  224. switch res.msg.Type {
  225. case MsgParse, MsgBind, MsgDescribe, MsgExecute, MsgClose:
  226. c.extendedCycle = true
  227. }
  228. if err := c.handleMessage(res.msg); err != nil {
  229. if err == io.EOF {
  230. log.Printf("Connection closed normally")
  231. return nil
  232. }
  233. log.Printf("Error handling message: %v", err)
  234. return err
  235. }
  236. case n := <-notifyCh:
  237. if err := c.sendNotification(n); err != nil {
  238. return err
  239. }
  240. if err := c.writer.Flush(); err != nil {
  241. return err
  242. }
  243. case <-overflow:
  244. return fmt.Errorf("notification queue overflow: slow consumer disconnected")
  245. }
  246. }
  247. }
  248. // initDatabase initializes the database connection
  249. func (c *Connection) initDatabase(dbName string) error {
  250. db, err := c.dbManager.GetDatabase(dbName)
  251. if err != nil {
  252. return err
  253. }
  254. c.schema = db.Schema
  255. c.table = db.Table
  256. c.executor = executor.New(db.Schema, db.Table)
  257. c.executor.SetBackendPID(c.backendPID)
  258. c.executor.SetNotificationHub(db.Hub)
  259. c.executor.SyncCatalog()
  260. return nil
  261. }
  262. // handleMessage processes a client message
  263. func (c *Connection) handleMessage(msg *Message) error {
  264. if c.extendedFailed && msg.Type != MsgSync && msg.Type != MsgFlush && msg.Type != MsgTerminate {
  265. return nil
  266. }
  267. switch msg.Type {
  268. case MsgProxyError:
  269. return c.handleProxyError(msg)
  270. case MsgQuery:
  271. return c.handleQuery(msg)
  272. case MsgTerminate:
  273. log.Printf("Client requested termination")
  274. return io.EOF
  275. case MsgParse:
  276. return c.handleParse(msg)
  277. case MsgBind:
  278. return c.handleBind(msg)
  279. case MsgDescribe:
  280. return c.handleDescribe(msg)
  281. case MsgExecute:
  282. return c.handleExecute(msg)
  283. case MsgClose:
  284. return c.handleClose(msg)
  285. case MsgFlush:
  286. return c.writer.Flush()
  287. case MsgSync:
  288. c.extendedFailed = false
  289. c.extendedCycle = false
  290. if err := c.sendReadyForQuery(); err != nil {
  291. return err
  292. }
  293. return c.drainNotifications()
  294. default:
  295. log.Printf("Unknown message type: %c (%d)", msg.Type, msg.Type)
  296. c.sendError("ERROR", ErrCodeProtocolViolation, fmt.Sprintf("Unknown message type: %c", msg.Type))
  297. return c.sendReadyForQuery()
  298. }
  299. }
  300. // handleQuery processes a simple query
  301. func (c *Connection) handleQuery(msg *Message) error {
  302. // A Query message carries a single NUL-terminated query string.
  303. if len(msg.Data) == 0 || msg.Data[len(msg.Data)-1] != 0 {
  304. c.sendError("ERROR", ErrCodeProtocolViolation, "invalid Query message: missing null terminator")
  305. return c.sendReadyForQuery()
  306. }
  307. sql := string(msg.Data[:len(msg.Data)-1])
  308. if !c.quiet {
  309. log.Printf("Query: %s", sql)
  310. }
  311. // Handle empty query
  312. sqlTrimmed := strings.TrimSpace(sql)
  313. if sqlTrimmed == "" || sqlTrimmed == ";" {
  314. if err := c.sendEmptyQueryResponse(); err != nil {
  315. return err
  316. }
  317. return c.sendReadyForQuery()
  318. }
  319. // Handle special PostgreSQL system queries that drivers send
  320. singleStatement := isSingleStatementSQL(sql)
  321. // In a failed transaction only ROLLBACK (or ROLLBACK TO SAVEPOINT) is
  322. // accepted. Gate before honoring the special driver queries below so they
  323. // return 25P02 instead of a result. Multi-statement batches are gated
  324. // per statement in the execution loop below.
  325. if c.txStatus == TxStatusFailed && singleStatement && !isRollbackStatement(sql) {
  326. c.sendError("ERROR", ErrCodeTransactionAborted, "current transaction is aborted, commands ignored until end of transaction block")
  327. return c.sendReadyForQuery()
  328. }
  329. // Recognize only complete initialization-query token sequences.
  330. if singleStatement {
  331. switch kind := systemQueryKind(sql); kind {
  332. case "version":
  333. return c.handleVersionQuery()
  334. case "current_user":
  335. return c.handleCurrentUserQuery()
  336. case "server_version", "server_encoding", "client_encoding":
  337. return c.handleShowCommand(strings.ToUpper(kind))
  338. }
  339. }
  340. if result, handled, err := c.catalogResult(sql); handled {
  341. if err != nil {
  342. c.sendError("ERROR", ErrCodeInternalError, err.Error())
  343. return c.sendReadyForQuery()
  344. }
  345. if err := c.sendTabularResult(result, "SELECT"); err != nil {
  346. return err
  347. }
  348. return c.sendReadyForQuery()
  349. }
  350. // Parse the complete batch before executing its first statement. This keeps
  351. // unsupported trailing clauses from turning into committed writes.
  352. l := lexer.New(sql)
  353. p := parser.New(l)
  354. stmts, err := p.ParseMultiple()
  355. if err != nil {
  356. code := ErrCodeSyntaxError
  357. if errors.Is(err, pgerror.ErrFeatureNotSupported) {
  358. code = ErrCodeFeatureNotSupported
  359. }
  360. if c.txStatus == TxStatusInBlock {
  361. c.txStatus = TxStatusFailed
  362. }
  363. c.sendError("ERROR", code, fmt.Sprintf("Syntax error: %v", err))
  364. return c.sendReadyForQuery()
  365. }
  366. for _, stmt := range stmts {
  367. if c.txStatus == TxStatusFailed {
  368. if _, rollback := stmt.(*parser.RollbackStmt); !rollback {
  369. c.sendError("ERROR", ErrCodeTransactionAborted, "current transaction is aborted, commands ignored until end of transaction block")
  370. return c.sendReadyForQuery()
  371. }
  372. }
  373. result, err := c.executor.Execute(stmt)
  374. if err != nil && isIdleRollback(stmt, c.txStatus, err) {
  375. result, err = executor.NewResult("ROLLBACK"), nil
  376. }
  377. if err != nil {
  378. code := ErrCodeInternalError
  379. message := fmt.Sprintf("Execution error: %v", err)
  380. var primaryKeyErr *storage.PrimaryKeyViolationError
  381. var uniqueErr *storage.UniqueViolationError
  382. var notNullErr *storage.NotNullViolationError
  383. var checkErr *storage.CheckViolationError
  384. var foreignKeyErr *storage.ForeignKeyViolationError
  385. if errors.Is(err, storage.ErrSerialization) {
  386. code = ErrCodeSerializationFailure
  387. c.txStatus = TxStatusIdle
  388. } else if errors.Is(err, pgerror.ErrInvalidText) {
  389. code = ErrCodeInvalidText
  390. if c.txStatus == TxStatusInBlock {
  391. c.txStatus = TxStatusFailed
  392. }
  393. } else if errors.Is(err, pgerror.ErrDatatypeMismatch) {
  394. code = ErrCodeDatatypeMismatch
  395. if c.txStatus == TxStatusInBlock {
  396. c.txStatus = TxStatusFailed
  397. }
  398. } else if analysisErr := analysisTypeMismatch(err); analysisErr {
  399. code = ErrCodeDatatypeMismatch
  400. if c.txStatus == TxStatusInBlock {
  401. c.txStatus = TxStatusFailed
  402. }
  403. } else if errors.As(err, &notNullErr) {
  404. code = "23502"
  405. if _, commit := stmt.(*parser.CommitStmt); commit {
  406. c.txStatus = TxStatusIdle
  407. } else if c.txStatus == TxStatusInBlock {
  408. c.txStatus = TxStatusFailed
  409. }
  410. } else if errors.As(err, &checkErr) {
  411. code = ErrCodeCheckViolation
  412. if _, commit := stmt.(*parser.CommitStmt); commit {
  413. c.txStatus = TxStatusIdle
  414. } else if c.txStatus == TxStatusInBlock {
  415. c.txStatus = TxStatusFailed
  416. }
  417. } else if errors.As(err, &foreignKeyErr) {
  418. code = ErrCodeForeignKeyViolation
  419. if _, commit := stmt.(*parser.CommitStmt); commit {
  420. c.txStatus = TxStatusIdle
  421. } else if c.txStatus == TxStatusInBlock {
  422. c.txStatus = TxStatusFailed
  423. }
  424. } else if errors.As(err, &uniqueErr) || errors.As(err, &primaryKeyErr) {
  425. code = ErrCodeUniqueViolation
  426. if uniqueErr != nil {
  427. message = fmt.Sprintf("Execution error: UNIQUE constraint failed: %s", uniqueErr.Constraint)
  428. }
  429. if _, commit := stmt.(*parser.CommitStmt); commit {
  430. c.txStatus = TxStatusIdle
  431. } else if c.txStatus == TxStatusInBlock {
  432. c.txStatus = TxStatusFailed
  433. }
  434. } else if errors.Is(err, pgerror.ErrFeatureNotSupported) || errors.Is(err, executor.ErrUnsupportedFeature) {
  435. code = ErrCodeFeatureNotSupported
  436. if c.txStatus == TxStatusInBlock {
  437. c.txStatus = TxStatusFailed
  438. }
  439. } else if _, commit := stmt.(*parser.CommitStmt); commit {
  440. // A failed COMMIT has already rolled the transaction back in
  441. // storage; leaving the session in the failed state would make
  442. // every following statement (including ROLLBACK) fail.
  443. c.txStatus = TxStatusIdle
  444. } else if c.txStatus == TxStatusInBlock {
  445. c.txStatus = TxStatusFailed
  446. }
  447. c.sendError("ERROR", code, message)
  448. return c.sendReadyForQuery()
  449. }
  450. if err := c.sendResult(result, stmt); err != nil {
  451. return err
  452. }
  453. if result.LSN > 0 {
  454. if err := c.sendLSN(result.LSN); err != nil {
  455. return err
  456. }
  457. }
  458. }
  459. return c.sendReadyForQuery()
  460. }
  461. func (c *Connection) handleParse(msg *Message) error {
  462. if c.extendedFailed {
  463. return nil
  464. }
  465. name, pos, err := readCString(msg.Data, 0)
  466. if err != nil {
  467. return c.failExtended(ErrCodeProtocolViolation, err)
  468. }
  469. query, pos, err := readCString(msg.Data, pos)
  470. if err != nil || pos+2 > len(msg.Data) {
  471. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Parse message"))
  472. }
  473. count := int(binary.BigEndian.Uint16(msg.Data[pos : pos+2]))
  474. pos += 2
  475. if pos+count*4 != len(msg.Data) {
  476. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Parse parameter list"))
  477. }
  478. oids := make([]int32, count)
  479. for i := range oids {
  480. oids[i] = int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  481. pos += 4
  482. }
  483. if !isSingleStatementSQL(query) {
  484. return c.failExtended(ErrCodeSyntaxError, fmt.Errorf("prepared statements must contain one command"))
  485. }
  486. c.statements[name] = &preparedStatement{query: query, paramOIDs: oids}
  487. return c.writeMessage(MsgParseComplete, nil)
  488. }
  489. func (c *Connection) handleBind(msg *Message) error {
  490. if c.extendedFailed {
  491. return nil
  492. }
  493. portalName, pos, err := readCString(msg.Data, 0)
  494. if err != nil {
  495. return c.failExtended(ErrCodeProtocolViolation, err)
  496. }
  497. statementName, pos, err := readCString(msg.Data, pos)
  498. if err != nil {
  499. return c.failExtended(ErrCodeProtocolViolation, err)
  500. }
  501. statement, ok := c.statements[statementName]
  502. if !ok {
  503. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("prepared statement %q does not exist", statementName))
  504. }
  505. formats, pos, err := readInt16List(msg.Data, pos)
  506. if err != nil || pos+2 > len(msg.Data) {
  507. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind format list"))
  508. }
  509. paramCount := int(binary.BigEndian.Uint16(msg.Data[pos : pos+2]))
  510. pos += 2
  511. if len(formats) > 1 && len(formats) != paramCount {
  512. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("Bind parameter format count does not match parameters"))
  513. }
  514. for _, format := range formats {
  515. if format != 0 && format != 1 {
  516. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter format code"))
  517. }
  518. }
  519. params := make([]boundParameter, paramCount)
  520. for i := range params {
  521. if pos+4 > len(msg.Data) {
  522. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter"))
  523. }
  524. length := int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  525. pos += 4
  526. params[i].oid = parameterOID(statement.paramOIDs, i)
  527. params[i].format = parameterFormat(formats, i)
  528. if length == -1 {
  529. params[i].null = true
  530. continue
  531. }
  532. if length < 0 || pos+int(length) > len(msg.Data) {
  533. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter length"))
  534. }
  535. params[i].value = append([]byte(nil), msg.Data[pos:pos+int(length)]...)
  536. pos += int(length)
  537. }
  538. resultFormats, pos, err := readInt16List(msg.Data, pos)
  539. if err != nil || pos != len(msg.Data) {
  540. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind result format list"))
  541. }
  542. for _, format := range resultFormats {
  543. if format != 0 && format != 1 {
  544. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind result format code"))
  545. }
  546. if format == 1 {
  547. return c.failExtended(ErrCodeFeatureNotSupported, fmt.Errorf("binary result format is not supported; request text results"))
  548. }
  549. }
  550. if len(resultFormats) > 1 {
  551. return c.failExtended(ErrCodeFeatureNotSupported, fmt.Errorf("per-column result format lists are not supported; request all-text results"))
  552. }
  553. query, err := bindQuery(statement.query, params)
  554. if err != nil {
  555. code := ErrCodeInvalidParameter
  556. if errors.Is(err, pgerror.ErrFeatureNotSupported) {
  557. code = ErrCodeFeatureNotSupported
  558. }
  559. if errors.Is(err, pgerror.ErrInvalidText) {
  560. code = ErrCodeInvalidText
  561. }
  562. return c.failExtended(code, err)
  563. }
  564. c.portals[portalName] = &portal{query: query}
  565. return c.writeMessage(MsgBindComplete, nil)
  566. }
  567. func (c *Connection) handleDescribe(msg *Message) error {
  568. if c.extendedFailed {
  569. return nil
  570. }
  571. if len(msg.Data) < 2 {
  572. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe message"))
  573. }
  574. name, pos, err := readCString(msg.Data, 1)
  575. if err != nil || pos != len(msg.Data) {
  576. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe name"))
  577. }
  578. switch msg.Data[0] {
  579. case 'S':
  580. statement, ok := c.statements[name]
  581. if !ok {
  582. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("prepared statement %q does not exist", name))
  583. }
  584. mb := NewMessageBuilder()
  585. mb.WriteInt16(int16(len(statement.paramOIDs)))
  586. for _, oid := range statement.paramOIDs {
  587. mb.WriteInt32(oid)
  588. }
  589. if err := c.writeMessage(MsgParameterDescription, mb.Bytes()); err != nil {
  590. return err
  591. }
  592. case 'P':
  593. if _, ok := c.portals[name]; !ok {
  594. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("portal %q does not exist", name))
  595. }
  596. default:
  597. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe target"))
  598. }
  599. // Row metadata requires analysis without side effects. Return NoData for
  600. // compatibility; Execute still emits the real RowDescription. This is the
  601. // pre-0.4.0 behavior used by common extended-protocol clients.
  602. return c.writeMessage(MsgNoData, nil)
  603. }
  604. func (c *Connection) handleExecute(msg *Message) error {
  605. if c.extendedFailed {
  606. return nil
  607. }
  608. name, pos, err := readCString(msg.Data, 0)
  609. if err != nil || pos+4 != len(msg.Data) {
  610. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Execute message"))
  611. }
  612. portal, ok := c.portals[name]
  613. if !ok {
  614. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("portal %q does not exist", name))
  615. }
  616. if portal.executed {
  617. return c.failExtended(ErrCodeFeatureNotSupported, fmt.Errorf("portal can only be executed once"))
  618. }
  619. maxRows := int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  620. if maxRows < 0 {
  621. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Execute row limit"))
  622. }
  623. // Check the transaction state before catalog emulation. Catalog queries do
  624. // not all parse as regular PizzaSQL statements, but must still return 25P02
  625. // while the transaction is aborted.
  626. if c.txStatus == TxStatusFailed && !isRollbackStatement(portal.query) {
  627. return c.failExtended(ErrCodeTransactionAborted, fmt.Errorf("current transaction is aborted, commands ignored until end of transaction block"))
  628. }
  629. if maxRows != 0 {
  630. return c.failExtended(ErrCodeFeatureNotSupported, fmt.Errorf("bounded Execute is not supported; use maxRows=0"))
  631. }
  632. portal.executed = true
  633. if result, handled, catalogErr := c.catalogResult(portal.query); handled {
  634. if catalogErr != nil {
  635. return c.failExtended(ErrCodeInternalError, catalogErr)
  636. }
  637. return c.sendTabularResult(result, "SELECT")
  638. }
  639. l := lexer.New(portal.query)
  640. stmt, err := parser.New(l).Parse()
  641. if err != nil {
  642. code := ErrCodeSyntaxError
  643. if errors.Is(err, pgerror.ErrFeatureNotSupported) {
  644. code = ErrCodeFeatureNotSupported
  645. if c.txStatus == TxStatusInBlock {
  646. c.txStatus = TxStatusFailed
  647. }
  648. }
  649. return c.failExtended(code, fmt.Errorf("syntax error: %w", err))
  650. }
  651. result, err := c.executor.Execute(stmt)
  652. if err != nil && isIdleRollback(stmt, c.txStatus, err) {
  653. result, err = executor.NewResult("ROLLBACK"), nil
  654. }
  655. if err != nil {
  656. code := ErrCodeInternalError
  657. var primaryKeyErr *storage.PrimaryKeyViolationError
  658. var uniqueErr *storage.UniqueViolationError
  659. var notNullErr *storage.NotNullViolationError
  660. var checkErr *storage.CheckViolationError
  661. var foreignKeyErr *storage.ForeignKeyViolationError
  662. if errors.Is(err, storage.ErrSerialization) {
  663. code = ErrCodeSerializationFailure
  664. c.txStatus = TxStatusIdle
  665. } else if errors.Is(err, pgerror.ErrInvalidText) {
  666. code = ErrCodeInvalidText
  667. if c.txStatus == TxStatusInBlock {
  668. c.txStatus = TxStatusFailed
  669. }
  670. } else if errors.Is(err, pgerror.ErrDatatypeMismatch) {
  671. code = ErrCodeDatatypeMismatch
  672. if c.txStatus == TxStatusInBlock {
  673. c.txStatus = TxStatusFailed
  674. }
  675. } else if analysisTypeMismatch(err) {
  676. code = ErrCodeDatatypeMismatch
  677. if c.txStatus == TxStatusInBlock {
  678. c.txStatus = TxStatusFailed
  679. }
  680. } else if errors.As(err, &notNullErr) {
  681. code = "23502"
  682. if _, commit := stmt.(*parser.CommitStmt); commit {
  683. c.txStatus = TxStatusIdle
  684. } else if c.txStatus == TxStatusInBlock {
  685. c.txStatus = TxStatusFailed
  686. }
  687. } else if errors.As(err, &checkErr) {
  688. code = ErrCodeCheckViolation
  689. if _, commit := stmt.(*parser.CommitStmt); commit {
  690. c.txStatus = TxStatusIdle
  691. } else if c.txStatus == TxStatusInBlock {
  692. c.txStatus = TxStatusFailed
  693. }
  694. } else if errors.As(err, &foreignKeyErr) {
  695. code = ErrCodeForeignKeyViolation
  696. if _, commit := stmt.(*parser.CommitStmt); commit {
  697. c.txStatus = TxStatusIdle
  698. } else if c.txStatus == TxStatusInBlock {
  699. c.txStatus = TxStatusFailed
  700. }
  701. } else if errors.As(err, &uniqueErr) || errors.As(err, &primaryKeyErr) {
  702. code = ErrCodeUniqueViolation
  703. if _, commit := stmt.(*parser.CommitStmt); commit {
  704. c.txStatus = TxStatusIdle
  705. } else if c.txStatus == TxStatusInBlock {
  706. c.txStatus = TxStatusFailed
  707. }
  708. } else if errors.Is(err, pgerror.ErrFeatureNotSupported) || errors.Is(err, executor.ErrUnsupportedFeature) {
  709. code = ErrCodeFeatureNotSupported
  710. if c.txStatus == TxStatusInBlock {
  711. c.txStatus = TxStatusFailed
  712. }
  713. } else if _, commit := stmt.(*parser.CommitStmt); commit {
  714. c.txStatus = TxStatusIdle
  715. } else if c.txStatus == TxStatusInBlock {
  716. c.txStatus = TxStatusFailed
  717. }
  718. if uniqueErr != nil {
  719. return c.failExtended(code, fmt.Errorf("execution error: UNIQUE constraint failed: %s", uniqueErr.Constraint))
  720. }
  721. return c.failExtended(code, fmt.Errorf("execution error: %w", err))
  722. }
  723. if err := c.sendResult(result, stmt); err != nil {
  724. return err
  725. }
  726. if result.LSN > 0 {
  727. return c.sendLSN(result.LSN)
  728. }
  729. return nil
  730. }
  731. // catalogSession is the catalog view this connection serves. The executor's
  732. // session is authoritative because it resolves against the transaction-scoped
  733. // DDL overlay, so catalog emulation inside a transaction sees staged tables,
  734. // columns, and indexes. The fallback only covers a connection that has not
  735. // completed startup yet.
  736. func (c *Connection) catalogSession() *storage.Session {
  737. if c.executor != nil {
  738. return c.executor.Session()
  739. }
  740. if c.schema == nil || c.table == nil {
  741. return nil
  742. }
  743. if c.catalogFallback == nil {
  744. c.catalogFallback = storage.NewSession(c.schema, c.table)
  745. }
  746. return c.catalogFallback
  747. }
  748. var catalogFilterPattern = regexp.MustCompile(`(?i)\b(table_name|tablename|table_schema|schemaname|constraint_name|indexname)\s*=\s*'((?:''|[^'])*)'`)
  749. func (c *Connection) catalogResult(sql string) (*executor.Result, bool, error) {
  750. if !isSingleStatementSQL(sql) {
  751. return nil, false, nil
  752. }
  753. source := catalogSource(sql)
  754. if source == "" {
  755. return nil, false, nil
  756. }
  757. session := c.catalogSession()
  758. if session == nil {
  759. return nil, false, nil
  760. }
  761. tables, err := session.ListTables()
  762. if err != nil {
  763. return nil, true, err
  764. }
  765. rows := make([]map[string]interface{}, 0)
  766. switch source {
  767. case "INFORMATION_SCHEMA.TABLES":
  768. for _, table := range tables {
  769. rows = append(rows, map[string]interface{}{
  770. "table_catalog": c.database, "table_schema": "public", "table_name": table, "table_type": "BASE TABLE",
  771. })
  772. }
  773. case "PG_TABLES":
  774. for _, table := range tables {
  775. indexes, _ := session.ListTableIndexes(table)
  776. rows = append(rows, map[string]interface{}{
  777. "schemaname": "public", "tablename": table, "tableowner": c.params["user"], "tablespace": nil,
  778. "hasindexes": len(indexes) > 0, "hasrules": false, "hastriggers": false, "rowsecurity": false,
  779. })
  780. }
  781. case "INFORMATION_SCHEMA.COLUMNS":
  782. for _, table := range tables {
  783. schema, schemaErr := session.GetSchema(table)
  784. if schemaErr != nil {
  785. continue
  786. }
  787. for i, column := range schema.Columns {
  788. rows = append(rows, map[string]interface{}{
  789. "table_catalog": c.database, "table_schema": "public", "table_name": table,
  790. "column_name": column.Name, "ordinal_position": int64(i + 1), "column_default": column.DefaultLiteral(),
  791. "is_nullable": yesNo(column.Nullable), "data_type": strings.ToLower(column.Type),
  792. })
  793. }
  794. }
  795. case "INFORMATION_SCHEMA.TABLE_CONSTRAINTS", "INFORMATION_SCHEMA.KEY_COLUMN_USAGE":
  796. for _, table := range tables {
  797. schema, schemaErr := session.GetSchema(table)
  798. if schemaErr != nil || schema.UsesSyntheticRowID() {
  799. continue
  800. }
  801. columns := schema.PrimaryKeyList()
  802. if source == "INFORMATION_SCHEMA.TABLE_CONSTRAINTS" {
  803. rows = append(rows, map[string]interface{}{
  804. "constraint_catalog": c.database, "constraint_schema": "public", "constraint_name": table + "_pkey",
  805. "table_catalog": c.database, "table_schema": "public", "table_name": table,
  806. "constraint_type": "PRIMARY KEY", "is_deferrable": "NO", "initially_deferred": "NO",
  807. })
  808. continue
  809. }
  810. // KEY_COLUMN_USAGE reports one row per key column, in key order.
  811. for i, column := range columns {
  812. rows = append(rows, map[string]interface{}{
  813. "constraint_catalog": c.database, "constraint_schema": "public", "constraint_name": table + "_pkey",
  814. "table_catalog": c.database, "table_schema": "public", "table_name": table,
  815. "column_name": column, "ordinal_position": int64(i + 1),
  816. })
  817. }
  818. }
  819. case "PG_INDEXES":
  820. for _, table := range tables {
  821. indexes, _ := session.ListTableIndexes(table)
  822. for _, index := range indexes {
  823. columns := make([]string, len(index.Columns))
  824. for i, column := range index.Columns {
  825. columns[i] = column.Name
  826. }
  827. unique := ""
  828. if index.Unique {
  829. unique = "UNIQUE "
  830. }
  831. rows = append(rows, map[string]interface{}{
  832. "schemaname": "public", "tablename": table, "indexname": index.Name, "tablespace": nil,
  833. "indexdef": fmt.Sprintf("CREATE %sINDEX %s ON %s (%s)", unique, index.Name, table, strings.Join(columns, ", ")),
  834. })
  835. }
  836. }
  837. }
  838. for _, match := range catalogFilterPattern.FindAllStringSubmatch(sql, -1) {
  839. column, expected := strings.ToLower(match[1]), strings.ReplaceAll(match[2], "''", "'")
  840. filtered := rows[:0]
  841. for _, row := range rows {
  842. if value, ok := row[column]; ok && strings.EqualFold(fmt.Sprintf("%v", value), expected) {
  843. filtered = append(filtered, row)
  844. }
  845. }
  846. rows = filtered
  847. }
  848. columns := catalogProjection(sql, rows)
  849. result := executor.NewResult("SELECT")
  850. if len(columns) == 1 && columns[0] == "count(*)" {
  851. result.AddColumnWithType("count", "INTEGER")
  852. result.AddRow(int64(len(rows)))
  853. return result, true, nil
  854. }
  855. for _, column := range columns {
  856. columnType := "TEXT"
  857. if column == "ordinal_position" {
  858. columnType = "INTEGER"
  859. } else if strings.HasPrefix(column, "has") || column == "rowsecurity" {
  860. columnType = "BOOLEAN"
  861. }
  862. result.AddColumnWithType(column, columnType)
  863. }
  864. for _, row := range rows {
  865. values := make([]interface{}, len(columns))
  866. for i, column := range columns {
  867. values[i] = row[column]
  868. }
  869. result.AddRow(values...)
  870. }
  871. return result, true, nil
  872. }
  873. // isRollbackStatement reports whether sql parses as a single ROLLBACK
  874. // statement, including ROLLBACK TO SAVEPOINT.
  875. func isRollbackStatement(sql string) bool {
  876. stmt, err := parser.New(lexer.New(sql)).Parse()
  877. if err != nil {
  878. return false
  879. }
  880. _, ok := stmt.(*parser.RollbackStmt)
  881. return ok
  882. }
  883. func catalogProjection(sql string, rows []map[string]interface{}) []string {
  884. upper := strings.ToUpper(sql)
  885. selectPos, fromPos := strings.Index(upper, "SELECT"), strings.Index(upper, " FROM ")
  886. if selectPos < 0 || fromPos < 0 || fromPos <= selectPos+6 {
  887. return nil
  888. }
  889. projection := strings.TrimSpace(sql[selectPos+6 : fromPos])
  890. projection = strings.TrimSpace(strings.TrimPrefix(strings.ToUpper(projection), "DISTINCT "))
  891. if projection == "*" && len(rows) > 0 {
  892. columns := make([]string, 0, len(rows[0]))
  893. for column := range rows[0] {
  894. columns = append(columns, column)
  895. }
  896. sort.Strings(columns)
  897. return columns
  898. }
  899. parts := strings.Split(projection, ",")
  900. columns := make([]string, 0, len(parts))
  901. for _, part := range parts {
  902. column := strings.TrimSpace(part)
  903. if index := strings.Index(strings.ToUpper(column), " AS "); index >= 0 {
  904. column = strings.TrimSpace(column[:index])
  905. }
  906. if index := strings.LastIndex(column, "."); index >= 0 {
  907. column = column[index+1:]
  908. }
  909. columns = append(columns, strings.ToLower(strings.Trim(column, `"`)))
  910. }
  911. return columns
  912. }
  913. func yesNo(value bool) string {
  914. if value {
  915. return "YES"
  916. }
  917. return "NO"
  918. }
  919. func (c *Connection) sendTabularResult(result *executor.Result, tag string) error {
  920. if err := c.sendRowDescription(result.Columns, result.ColumnTypes); err != nil {
  921. return err
  922. }
  923. for _, row := range result.Rows {
  924. if err := c.sendDataRow(row, result.Columns); err != nil {
  925. return err
  926. }
  927. }
  928. return c.sendCommandComplete(fmt.Sprintf("%s %d", tag, len(result.Rows)))
  929. }
  930. func (c *Connection) handleClose(msg *Message) error {
  931. if c.extendedFailed {
  932. return nil
  933. }
  934. if len(msg.Data) < 2 {
  935. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close message"))
  936. }
  937. name, pos, err := readCString(msg.Data, 1)
  938. if err != nil || pos != len(msg.Data) {
  939. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close name"))
  940. }
  941. if msg.Data[0] == 'S' {
  942. delete(c.statements, name)
  943. } else if msg.Data[0] == 'P' {
  944. delete(c.portals, name)
  945. } else {
  946. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close target"))
  947. }
  948. return c.writeMessage(MsgCloseComplete, nil)
  949. }
  950. func (c *Connection) failExtended(code string, err error) error {
  951. c.extendedFailed = true
  952. if c.txStatus == TxStatusInBlock {
  953. c.txStatus = TxStatusFailed
  954. }
  955. return c.sendError("ERROR", code, err.Error())
  956. }
  957. func (c *Connection) handleProxyError(msg *Message) error {
  958. if len(msg.Data) != 1 || (msg.Data[0] != MsgQuery && msg.Data[0] != MsgParse) {
  959. _ = c.sendError("FATAL", ErrCodeProtocolViolation, "invalid proxy error relay")
  960. return io.EOF
  961. }
  962. code, message := "42501", "permission denied by API key scopes"
  963. if c.txStatus == TxStatusFailed {
  964. code, message = ErrCodeTransactionAborted, "current transaction is aborted, commands ignored until end of transaction block"
  965. }
  966. if msg.Data[0] == MsgParse {
  967. c.extendedCycle = true
  968. return c.failExtended(code, errors.New(message))
  969. }
  970. if c.txStatus == TxStatusInBlock {
  971. c.txStatus = TxStatusFailed
  972. }
  973. if err := c.sendError("ERROR", code, message); err != nil {
  974. return err
  975. }
  976. return c.sendReadyForQuery()
  977. }
  978. // analysisTypeMismatch reports whether the error is an analyzer type-mismatch,
  979. // which is reported with SQLSTATE 42804 instead of a generic internal error.
  980. func analysisTypeMismatch(err error) bool {
  981. var analysisErr *analyzer.AnalysisError
  982. return errors.As(err, &analysisErr) && analysisErr.Type == analyzer.ErrTypeMismatch
  983. }
  984. type boundParameter struct {
  985. value []byte
  986. oid int32
  987. format int16
  988. null bool
  989. }
  990. func readCString(data []byte, pos int) (string, int, error) {
  991. if pos < 0 || pos >= len(data) {
  992. return "", pos, fmt.Errorf("missing null-terminated string")
  993. }
  994. end := bytes.IndexByte(data[pos:], 0)
  995. if end < 0 {
  996. return "", pos, fmt.Errorf("unterminated string")
  997. }
  998. return string(data[pos : pos+end]), pos + end + 1, nil
  999. }
  1000. func readInt16List(data []byte, pos int) ([]int16, int, error) {
  1001. if pos+2 > len(data) {
  1002. return nil, pos, fmt.Errorf("missing list length")
  1003. }
  1004. count := int(binary.BigEndian.Uint16(data[pos : pos+2]))
  1005. pos += 2
  1006. if pos+count*2 > len(data) {
  1007. return nil, pos, fmt.Errorf("truncated list")
  1008. }
  1009. result := make([]int16, count)
  1010. for i := range result {
  1011. result[i] = int16(binary.BigEndian.Uint16(data[pos : pos+2]))
  1012. pos += 2
  1013. }
  1014. return result, pos, nil
  1015. }
  1016. func parameterOID(oids []int32, index int) int32 {
  1017. if index < len(oids) {
  1018. return oids[index]
  1019. }
  1020. return 0
  1021. }
  1022. func parameterFormat(formats []int16, index int) int16 {
  1023. if len(formats) == 1 {
  1024. return formats[0]
  1025. }
  1026. if index < len(formats) {
  1027. return formats[index]
  1028. }
  1029. return 0
  1030. }
  1031. func bindQuery(query string, params []boundParameter) (string, error) {
  1032. var result strings.Builder
  1033. var quote byte
  1034. for i := 0; i < len(query); {
  1035. ch := query[i]
  1036. if quote != 0 {
  1037. result.WriteByte(ch)
  1038. i++
  1039. if ch == quote {
  1040. if i < len(query) && query[i] == quote {
  1041. result.WriteByte(query[i])
  1042. i++
  1043. } else {
  1044. quote = 0
  1045. }
  1046. }
  1047. continue
  1048. }
  1049. if i+1 < len(query) && ch == '-' && query[i+1] == '-' {
  1050. end := strings.IndexByte(query[i:], '\n')
  1051. if end < 0 {
  1052. result.WriteString(query[i:])
  1053. break
  1054. }
  1055. result.WriteString(query[i : i+end+1])
  1056. i += end + 1
  1057. continue
  1058. }
  1059. if i+1 < len(query) && ch == '/' && query[i+1] == '*' {
  1060. end := strings.Index(query[i+2:], "*/")
  1061. if end < 0 {
  1062. result.WriteString(query[i:])
  1063. break
  1064. }
  1065. result.WriteString(query[i : i+end+4])
  1066. i += end + 4
  1067. continue
  1068. }
  1069. // Only string literals and quoted identifiers are skipped. Brackets are
  1070. // not a quoted region: a subscript such as tags[$1] must bind $1.
  1071. if ch == '\'' || ch == '"' || ch == '`' {
  1072. quote = ch
  1073. result.WriteByte(ch)
  1074. i++
  1075. continue
  1076. }
  1077. if ch == '$' && i+1 < len(query) && query[i+1] >= '0' && query[i+1] <= '9' {
  1078. end := i + 1
  1079. for end < len(query) && query[end] >= '0' && query[end] <= '9' {
  1080. end++
  1081. }
  1082. n, err := strconv.Atoi(query[i+1 : end])
  1083. if err != nil || n < 1 || n > len(params) {
  1084. return "", fmt.Errorf("parameter %s was not provided", query[i:end])
  1085. }
  1086. literal, err := parameterLiteral(params[n-1])
  1087. if err != nil {
  1088. return "", fmt.Errorf("parameter $%d: %w", n, err)
  1089. }
  1090. result.WriteString(literal)
  1091. i = end
  1092. continue
  1093. }
  1094. result.WriteByte(ch)
  1095. i++
  1096. }
  1097. return result.String(), nil
  1098. }
  1099. func parameterLiteral(param boundParameter) (string, error) {
  1100. if param.null {
  1101. return "NULL", nil
  1102. }
  1103. if param.format == 1 {
  1104. if _, isArray := arrayParamElementType(param.oid); isArray {
  1105. return "", fmt.Errorf("%w: binary array parameter format for OID %d; send arrays in text format", pgerror.ErrFeatureNotSupported, param.oid)
  1106. }
  1107. switch param.oid {
  1108. case 16:
  1109. if len(param.value) != 1 {
  1110. return "", fmt.Errorf("invalid binary boolean")
  1111. }
  1112. if param.value[0] == 0 {
  1113. return "FALSE", nil
  1114. }
  1115. return "TRUE", nil
  1116. case 21:
  1117. if len(param.value) != 2 {
  1118. return "", fmt.Errorf("invalid binary int2")
  1119. }
  1120. return strconv.FormatInt(int64(int16(binary.BigEndian.Uint16(param.value))), 10), nil
  1121. case 23:
  1122. if len(param.value) != 4 {
  1123. return "", fmt.Errorf("invalid binary int4")
  1124. }
  1125. return strconv.FormatInt(int64(int32(binary.BigEndian.Uint32(param.value))), 10), nil
  1126. case 20:
  1127. if len(param.value) != 8 {
  1128. return "", fmt.Errorf("invalid binary int8")
  1129. }
  1130. return strconv.FormatInt(int64(binary.BigEndian.Uint64(param.value)), 10), nil
  1131. default:
  1132. return "", fmt.Errorf("%w: binary parameter format for OID %d", pgerror.ErrFeatureNotSupported, param.oid)
  1133. }
  1134. }
  1135. value := string(param.value)
  1136. if element, isArray := arrayParamElementType(param.oid); isArray {
  1137. // The bound value is PostgreSQL array text. Validate and canonicalize it
  1138. // now so a malformed array fails at Bind instead of during row
  1139. // evaluation, then emit a typed literal the executor accepts unchanged.
  1140. arrayType := element + "[]"
  1141. canonical, err := executor.CanonicalizeArrayText(value, arrayType)
  1142. if err != nil {
  1143. return "", err
  1144. }
  1145. return "'" + strings.ReplaceAll(canonical, "'", "''") + "'::" + arrayType, nil
  1146. }
  1147. switch param.oid {
  1148. case 0:
  1149. if strings.EqualFold(value, "true") || strings.EqualFold(value, "false") {
  1150. return strings.ToUpper(value), nil
  1151. }
  1152. if _, err := strconv.ParseFloat(value, 64); err == nil && value != "" {
  1153. return value, nil
  1154. }
  1155. return "'" + strings.ReplaceAll(value, "'", "''") + "'", nil
  1156. case 16:
  1157. if strings.EqualFold(value, "true") || value == "1" || value == "t" {
  1158. return "TRUE", nil
  1159. }
  1160. return "FALSE", nil
  1161. case 20, 21, 23, 26, 700, 701, 1700:
  1162. if _, err := strconv.ParseFloat(value, 64); err != nil {
  1163. return "", fmt.Errorf("invalid numeric value")
  1164. }
  1165. return value, nil
  1166. default:
  1167. return "'" + strings.ReplaceAll(value, "'", "''") + "'", nil
  1168. }
  1169. }
  1170. // sendResult sends query results
  1171. func (c *Connection) sendResult(result *executor.Result, stmt parser.Statement) error {
  1172. // Any statement that produced a row set (SELECT, or INSERT/UPDATE/DELETE
  1173. // with RETURNING) sends a row description and its data rows. Other
  1174. // statements only send the command completion tag.
  1175. if len(result.Columns) > 0 {
  1176. if err := c.sendRowDescription(result.Columns, wireColumnTypes(result)); err != nil {
  1177. return err
  1178. }
  1179. for _, row := range result.Rows {
  1180. if err := c.sendDataRow(row, result.Columns); err != nil {
  1181. return err
  1182. }
  1183. }
  1184. return c.sendCommandComplete(c.getCommandTag(stmt, result))
  1185. }
  1186. // For other statements, just send command complete
  1187. tag := c.getCommandTag(stmt, result)
  1188. return c.sendCommandComplete(tag)
  1189. }
  1190. // wireColumnTypes corrects declared-affinity metadata when SQLite has stored a
  1191. // value of another type. In particular, binding []byte to a VARCHAR column is
  1192. // still a BLOB in SQLite; advertising TEXT while encoding PostgreSQL bytea text
  1193. // would make clients receive the literal "\\x..." instead of the original
  1194. // bytes.
  1195. func wireColumnTypes(result *executor.Result) []string {
  1196. types := append([]string(nil), result.ColumnTypes...)
  1197. if len(types) < len(result.Columns) {
  1198. types = append(types, make([]string, len(result.Columns)-len(types))...)
  1199. }
  1200. for _, row := range result.Rows {
  1201. for i, value := range row {
  1202. if i >= len(types) {
  1203. break
  1204. }
  1205. if _, ok := value.([]byte); ok {
  1206. types[i] = "BLOB"
  1207. }
  1208. }
  1209. }
  1210. return types
  1211. }
  1212. // getCommandTag returns the command completion tag
  1213. func (c *Connection) getCommandTag(stmt parser.Statement, result *executor.Result) string {
  1214. switch s := stmt.(type) {
  1215. case *parser.SelectStmt:
  1216. return fmt.Sprintf("SELECT %d", len(result.Rows))
  1217. case *parser.CreateTableStmt:
  1218. return "CREATE TABLE"
  1219. case *parser.DropTableStmt:
  1220. return "DROP TABLE"
  1221. case *parser.CreateIndexStmt:
  1222. return "CREATE INDEX"
  1223. case *parser.DropIndexStmt:
  1224. return "DROP INDEX"
  1225. case *parser.AlterTableStmt:
  1226. return "ALTER TABLE"
  1227. case *parser.InsertStmt:
  1228. return fmt.Sprintf("INSERT 0 %d", result.RowsAffected)
  1229. case *parser.UpdateStmt:
  1230. return fmt.Sprintf("UPDATE %d", result.RowsAffected)
  1231. case *parser.DeleteStmt:
  1232. return fmt.Sprintf("DELETE %d", result.RowsAffected)
  1233. case *parser.BeginStmt:
  1234. c.txStatus = TxStatusInBlock
  1235. return "BEGIN"
  1236. case *parser.CommitStmt:
  1237. c.txStatus = TxStatusIdle
  1238. return "COMMIT"
  1239. case *parser.RollbackStmt:
  1240. if s.Savepoint != "" {
  1241. c.txStatus = TxStatusInBlock
  1242. return "ROLLBACK"
  1243. }
  1244. c.txStatus = TxStatusIdle
  1245. return "ROLLBACK"
  1246. case *parser.SavepointStmt:
  1247. c.txStatus = TxStatusInBlock
  1248. return "SAVEPOINT"
  1249. case *parser.ReleaseStmt:
  1250. c.txStatus = TxStatusInBlock
  1251. return "RELEASE"
  1252. case *parser.ListenStmt:
  1253. return "LISTEN"
  1254. case *parser.UnlistenStmt:
  1255. return "UNLISTEN"
  1256. case *parser.NotifyStmt:
  1257. return "NOTIFY"
  1258. default:
  1259. return "OK"
  1260. }
  1261. }
  1262. // sendAuthenticationOk sends authentication OK message
  1263. func (c *Connection) sendAuthenticationOk() error {
  1264. mb := NewMessageBuilder()
  1265. mb.WriteInt32(0) // Auth OK
  1266. return c.writeMessage(MsgAuthenticationOk, mb.Bytes())
  1267. }
  1268. // drainNotifications writes every notification currently buffered for this
  1269. // session. It is called at protocol-safe points (after Sync/ReadyForQuery).
  1270. func (c *Connection) drainNotifications() error {
  1271. ch := c.executor.NotificationChannel()
  1272. for {
  1273. select {
  1274. case n := <-ch:
  1275. if err := c.sendNotification(n); err != nil {
  1276. return err
  1277. }
  1278. default:
  1279. return c.writer.Flush()
  1280. }
  1281. }
  1282. }
  1283. // sendNotification writes a NotificationResponse frame. The frame is only
  1284. // written by the connection's main goroutine, never from a publisher.
  1285. func (c *Connection) sendNotification(n storage.Notification) error {
  1286. mb := NewMessageBuilder()
  1287. mb.WriteInt32(n.PID)
  1288. mb.WriteString(n.Channel)
  1289. mb.WriteString(n.Payload)
  1290. return c.writeMessage(MsgNotificationResponse, mb.Bytes())
  1291. }
  1292. // sendLSN exposes the last commit LSN as a ParameterStatus. Drivers that do
  1293. // not know the key ignore it; subscribers can use it as an ordering cursor.
  1294. func (c *Connection) sendLSN(lsn uint64) error {
  1295. return c.sendParameterStatus("pizzasql.lsn", strconv.FormatUint(lsn, 10))
  1296. }
  1297. // sendParameterStatus sends a parameter status message
  1298. func (c *Connection) sendParameterStatus(name, value string) error {
  1299. mb := NewMessageBuilder()
  1300. mb.WriteString(name)
  1301. mb.WriteString(value)
  1302. return c.writeMessage(MsgParameterStatus, mb.Bytes())
  1303. }
  1304. // sendBackendKeyData sends backend key data
  1305. func (c *Connection) sendBackendKeyData(processID, secretKey int32) error {
  1306. mb := NewMessageBuilder()
  1307. mb.WriteInt32(processID)
  1308. mb.WriteInt32(secretKey)
  1309. return c.writeMessage(MsgBackendKeyData, mb.Bytes())
  1310. }
  1311. // isIdleRollback reports whether a bare ROLLBACK found no transaction to roll
  1312. // back. A COMMIT rejected by storage has already ended the transaction, so the
  1313. // client's cleanup ROLLBACK must complete (PostgreSQL reports a warning and
  1314. // succeeds) instead of surfacing an internal error on an idle session.
  1315. func isIdleRollback(stmt parser.Statement, status byte, err error) bool {
  1316. rollback, ok := stmt.(*parser.RollbackStmt)
  1317. if !ok || rollback.Savepoint != "" {
  1318. return false
  1319. }
  1320. return status == TxStatusIdle && errors.Is(err, executor.ErrNoTransaction)
  1321. }
  1322. // sendReadyForQuery sends ready for query message
  1323. func (c *Connection) sendReadyForQuery() error {
  1324. mb := NewMessageBuilder()
  1325. mb.AppendByte(c.txStatus)
  1326. if err := c.writeMessage(MsgReadyForQuery, mb.Bytes()); err != nil {
  1327. return err
  1328. }
  1329. // ReadyForQuery closes out a response cycle, so flush everything buffered
  1330. // so far. This is what makes simple-query results and Sync responses
  1331. // visible to the client.
  1332. return c.writer.Flush()
  1333. }
  1334. // sendEmptyQueryResponse sends empty query response
  1335. func (c *Connection) sendEmptyQueryResponse() error {
  1336. return c.writeMessage(MsgEmptyQueryResponse, []byte{})
  1337. }
  1338. // sendRowDescription sends row description (column metadata)
  1339. func (c *Connection) sendRowDescription(columns []string, columnTypes []string) error {
  1340. mb := NewMessageBuilder()
  1341. mb.WriteInt16(int16(len(columns)))
  1342. for i, col := range columns {
  1343. colType := ""
  1344. if i < len(columnTypes) {
  1345. colType = columnTypes[i]
  1346. }
  1347. mb.WriteString(col)
  1348. mb.WriteInt32(0) // table OID
  1349. mb.WriteInt16(0) // column attribute number
  1350. mb.WriteInt32(c.getOIDForType(colType)) // type OID
  1351. mb.WriteInt16(c.getTypeSizeForType(colType)) // type size
  1352. mb.WriteInt32(-1) // type modifier
  1353. mb.WriteInt16(0) // format code (text)
  1354. }
  1355. return c.writeMessage(MsgRowDescription, mb.Bytes())
  1356. }
  1357. // sendDataRow sends a data row
  1358. func (c *Connection) sendDataRow(row []interface{}, columns []string) error {
  1359. mb := NewMessageBuilder()
  1360. mb.WriteInt16(int16(len(row)))
  1361. for _, value := range row {
  1362. if value == nil {
  1363. mb.WriteInt32(-1) // NULL indicator
  1364. continue
  1365. }
  1366. // Convert value to string
  1367. strValue := c.valueToString(value)
  1368. mb.WriteInt32(int32(len(strValue)))
  1369. mb.WriteBytes([]byte(strValue))
  1370. }
  1371. return c.writeMessage(MsgDataRow, mb.Bytes())
  1372. }
  1373. // sendCommandComplete sends command complete message
  1374. func (c *Connection) sendCommandComplete(tag string) error {
  1375. mb := NewMessageBuilder()
  1376. mb.WriteString(tag)
  1377. return c.writeMessage(MsgCommandComplete, mb.Bytes())
  1378. }
  1379. // sendError sends an error response
  1380. func (c *Connection) sendError(severity, code, message string) error {
  1381. if severity == "ERROR" && c.txStatus == TxStatusInBlock {
  1382. c.txStatus = TxStatusFailed
  1383. }
  1384. mb := NewMessageBuilder()
  1385. mb.AppendByte(ErrorFieldSeverity)
  1386. mb.WriteString(severity)
  1387. mb.AppendByte(ErrorFieldCode)
  1388. mb.WriteString(code)
  1389. mb.AppendByte(ErrorFieldMessage)
  1390. mb.WriteString(message)
  1391. mb.AppendByte(0) // Terminator
  1392. if err := c.writeMessage(MsgErrorResponse, mb.Bytes()); err != nil {
  1393. return err
  1394. }
  1395. // Errors must be visible promptly, including FATAL startup failures that
  1396. // are not followed by a ReadyForQuery before the connection closes.
  1397. return c.writer.Flush()
  1398. }
  1399. // writeMessage buffers a message for the connection. It does not flush, so
  1400. // callers that need to make a response visible to the client must flush at the
  1401. // appropriate protocol boundary (ReadyForQuery, an explicit Flush message, or
  1402. // an error response). Buffering amortizes the per-message syscalls that a
  1403. // result set would otherwise incur; the underlying bufio.Writer bounds memory
  1404. // use so large result sets cannot grow the buffer without limit.
  1405. func (c *Connection) writeMessage(msgType byte, data []byte) error {
  1406. if !c.quiet {
  1407. log.Printf("Sending message type=%c length=%d", msgType, len(data)+4)
  1408. }
  1409. return WriteMessage(c.writer, msgType, data)
  1410. }
  1411. // arrayElementTypeName reports the element type of an array type name such as
  1412. // "INTEGER[]". It reports false for scalar type names.
  1413. func arrayElementTypeName(typeName string) (string, bool) {
  1414. upper := strings.ToUpper(strings.TrimSpace(typeName))
  1415. if !strings.HasSuffix(upper, "[]") {
  1416. return "", false
  1417. }
  1418. return strings.TrimSpace(strings.TrimSuffix(upper, "[]")), true
  1419. }
  1420. // arrayOIDForElement maps an array element type name to its PostgreSQL array
  1421. // OID. Narrower integer types report int8[] because values are not
  1422. // range-checked, matching the scalar carrier rule; NUMERIC reports numeric[]
  1423. // because array elements stay text.
  1424. func arrayOIDForElement(element string) int32 {
  1425. base := strings.ToUpper(strings.TrimSpace(element))
  1426. if idx := strings.IndexByte(base, '('); idx >= 0 {
  1427. base = strings.TrimSpace(base[:idx])
  1428. }
  1429. switch base {
  1430. case "INTEGER", "INT", "INT4":
  1431. return 1007 // INT4ARRAYOID
  1432. case "BIGINT", "INT8", "SMALLINT", "INT2", "TINYINT", "MEDIUMINT":
  1433. return 1016 // INT8ARRAYOID
  1434. case "BOOLEAN", "BOOL":
  1435. return 1000 // BOOLARRAYOID
  1436. case "REAL", "FLOAT", "FLOAT4":
  1437. return 1021 // FLOAT4ARRAYOID
  1438. case "DOUBLE", "DOUBLE PRECISION", "FLOAT8":
  1439. return 1022 // FLOAT8ARRAYOID
  1440. case "NUMERIC", "DECIMAL":
  1441. return 1231 // NUMERICARRAYOID
  1442. case "VARCHAR", "NVARCHAR", "CHARACTER VARYING":
  1443. return 1015 // VARCHARARRAYOID
  1444. default:
  1445. return 1009 // TEXTARRAYOID
  1446. }
  1447. }
  1448. // arrayParamElementType maps an array parameter OID to the element type the
  1449. // bound literal is cast to. Unknown OIDs are handled by callers.
  1450. func arrayParamElementType(oid int32) (string, bool) {
  1451. switch oid {
  1452. case 1009:
  1453. return "TEXT", true
  1454. case 1015:
  1455. return "VARCHAR", true
  1456. case 1007:
  1457. return "INTEGER", true
  1458. case 1016:
  1459. return "BIGINT", true
  1460. case 1005:
  1461. return "SMALLINT", true
  1462. case 1000:
  1463. return "BOOLEAN", true
  1464. case 1021:
  1465. return "REAL", true
  1466. case 1022:
  1467. return "DOUBLE", true
  1468. case 1231:
  1469. return "NUMERIC", true
  1470. default:
  1471. return "", false
  1472. }
  1473. }
  1474. // getOIDForType returns PostgreSQL OID for type.
  1475. //
  1476. // Types narrower than the value the engine carries are reported as the carrier
  1477. // type, because the engine does not range-check stored or cast values: a value
  1478. // that does not fit int2/int4 or float4 would fail client-side decoding rather
  1479. // than having been rejected on write. INTEGER and REAL keep their declared
  1480. // mappings, which predate this rule and are what existing clients expect.
  1481. func (c *Connection) getOIDForType(typeName string) int32 {
  1482. if element, ok := arrayElementTypeName(typeName); ok {
  1483. return arrayOIDForElement(element)
  1484. }
  1485. switch strings.ToUpper(typeName) {
  1486. case "SMALLINT", "INT2", "TINYINT", "MEDIUMINT":
  1487. // Carried as int64 and not range-checked, so int8 is the honest type.
  1488. return 20 // INT8OID
  1489. case "INTEGER", "INT", "INT4":
  1490. return 23 // INT4OID
  1491. case "BIGINT", "INT8":
  1492. return 20 // INT8OID
  1493. case "NUMERIC", "DECIMAL":
  1494. // Values round-trip through JSON as float64; there is no exact decimal
  1495. // carrier, so NUMERIC is not advertised.
  1496. return 701 // FLOAT8OID
  1497. case "TEXT", "VARCHAR", "CHAR", "UUID":
  1498. // UUID is stored as text (SQLite-style), so it reports TEXTOID rather
  1499. // than the native PG UUID OID.
  1500. return 25 // TEXTOID
  1501. case "REAL", "FLOAT":
  1502. return 700 // FLOAT4OID
  1503. case "DOUBLE":
  1504. return 701 // FLOAT8OID
  1505. case "BOOLEAN", "BOOL":
  1506. return 16 // BOOLOID
  1507. case "BLOB":
  1508. return 17 // BYTEAOID
  1509. case "DATETIME", "TIMESTAMP":
  1510. // Datetime values are exchanged as UTC RFC3339 (ISO8601 with a timezone
  1511. // offset), which timestamptz decodes directly.
  1512. return 1184 // TIMESTAMPTZOID
  1513. case "DATE":
  1514. return 1082 // DATEOID
  1515. default:
  1516. return 25 // Default to TEXT
  1517. }
  1518. }
  1519. // getTypeSizeForType returns type size in bytes, or -1 for variable length.
  1520. func (c *Connection) getTypeSizeForType(typeName string) int16 {
  1521. if _, ok := arrayElementTypeName(typeName); ok {
  1522. return -1 // arrays are variable length
  1523. }
  1524. switch strings.ToUpper(typeName) {
  1525. case "SMALLINT", "INT2", "TINYINT", "MEDIUMINT":
  1526. return 8 // Reported as int8; see getOIDForType.
  1527. case "INTEGER", "INT", "INT4":
  1528. return 4
  1529. case "BIGINT", "INT8":
  1530. return 8
  1531. case "NUMERIC", "DECIMAL":
  1532. return 8 // Reported as float8; see getOIDForType.
  1533. case "REAL", "FLOAT":
  1534. return 4
  1535. case "DOUBLE":
  1536. return 8
  1537. case "BOOLEAN", "BOOL":
  1538. return 1
  1539. case "DATETIME", "TIMESTAMP":
  1540. return 8
  1541. case "DATE":
  1542. return 4
  1543. default:
  1544. return -1 // Variable length
  1545. }
  1546. }
  1547. // valueToString converts a value to string
  1548. func (c *Connection) valueToString(value interface{}) string {
  1549. if value == nil {
  1550. return ""
  1551. }
  1552. // PostgreSQL's text format for bytea is \x followed by hex. Emitting that
  1553. // lets libpq/pgx decode a BLOB column (OID 17) losslessly.
  1554. if b, ok := value.([]byte); ok {
  1555. return `\x` + hex.EncodeToString(b)
  1556. }
  1557. return fmt.Sprintf("%v", value)
  1558. }
  1559. // handleVersionQuery handles SELECT version()
  1560. func (c *Connection) handleVersionQuery() error {
  1561. columns := []string{"version"}
  1562. columnTypes := []string{"TEXT"}
  1563. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1564. return err
  1565. }
  1566. row := []interface{}{"PostgreSQL " + version.PostgreSQLCompatVersion + " (PizzaSQL)"}
  1567. if err := c.sendDataRow(row, columns); err != nil {
  1568. return err
  1569. }
  1570. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1571. return err
  1572. }
  1573. return c.sendReadyForQuery()
  1574. }
  1575. // handleCurrentUserQuery handles SELECT current_user
  1576. func (c *Connection) handleCurrentUserQuery() error {
  1577. columns := []string{"current_user"}
  1578. columnTypes := []string{"TEXT"}
  1579. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1580. return err
  1581. }
  1582. user := c.params["user"]
  1583. if user == "" {
  1584. user = "pizzasql"
  1585. }
  1586. row := []interface{}{user}
  1587. if err := c.sendDataRow(row, columns); err != nil {
  1588. return err
  1589. }
  1590. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1591. return err
  1592. }
  1593. return c.sendReadyForQuery()
  1594. }
  1595. // handleShowCommand handles SHOW commands
  1596. func (c *Connection) handleShowCommand(sqlUpper string) error {
  1597. var value string
  1598. var name string
  1599. if sqlUpper == "SERVER_VERSION" {
  1600. name = "server_version"
  1601. value = version.PostgreSQLCompatVersion
  1602. } else if sqlUpper == "SERVER_ENCODING" {
  1603. name = "server_encoding"
  1604. value = "UTF8"
  1605. } else if sqlUpper == "CLIENT_ENCODING" {
  1606. name = "client_encoding"
  1607. value = "UTF8"
  1608. } else {
  1609. // Unknown SHOW command
  1610. c.sendError("ERROR", ErrCodeFeatureNotSupported, "SHOW command not supported")
  1611. return c.sendReadyForQuery()
  1612. }
  1613. columns := []string{name}
  1614. columnTypes := []string{"TEXT"}
  1615. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1616. return err
  1617. }
  1618. row := []interface{}{value}
  1619. if err := c.sendDataRow(row, columns); err != nil {
  1620. return err
  1621. }
  1622. if err := c.sendCommandComplete("SHOW"); err != nil {
  1623. return err
  1624. }
  1625. return c.sendReadyForQuery()
  1626. }