connection.go 59 KB

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