connection.go 63 KB

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