connection.go 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778
  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 analysisErr := analysisTypeMismatch(err); analysisErr {
  428. code = ErrCodeDatatypeMismatch
  429. if c.txStatus == TxStatusInBlock {
  430. c.txStatus = TxStatusFailed
  431. }
  432. } else if errors.As(err, &notNullErr) {
  433. code = "23502"
  434. if _, commit := stmt.(*parser.CommitStmt); commit {
  435. c.txStatus = TxStatusIdle
  436. } else if c.txStatus == TxStatusInBlock {
  437. c.txStatus = TxStatusFailed
  438. }
  439. } else if errors.As(err, &checkErr) {
  440. code = ErrCodeCheckViolation
  441. if _, commit := stmt.(*parser.CommitStmt); commit {
  442. c.txStatus = TxStatusIdle
  443. } else if c.txStatus == TxStatusInBlock {
  444. c.txStatus = TxStatusFailed
  445. }
  446. } else if errors.As(err, &foreignKeyErr) {
  447. code = ErrCodeForeignKeyViolation
  448. if _, commit := stmt.(*parser.CommitStmt); commit {
  449. c.txStatus = TxStatusIdle
  450. } else if c.txStatus == TxStatusInBlock {
  451. c.txStatus = TxStatusFailed
  452. }
  453. } else if errors.As(err, &uniqueErr) || errors.As(err, &primaryKeyErr) {
  454. code = ErrCodeUniqueViolation
  455. if uniqueErr != nil {
  456. message = fmt.Sprintf("Execution error: UNIQUE constraint failed: %s", uniqueErr.Constraint)
  457. }
  458. if _, commit := stmt.(*parser.CommitStmt); commit {
  459. c.txStatus = TxStatusIdle
  460. } else if c.txStatus == TxStatusInBlock {
  461. c.txStatus = TxStatusFailed
  462. }
  463. } else if errors.Is(err, pgerror.ErrFeatureNotSupported) || errors.Is(err, executor.ErrUnsupportedFeature) {
  464. code = ErrCodeFeatureNotSupported
  465. if c.txStatus == TxStatusInBlock {
  466. c.txStatus = TxStatusFailed
  467. }
  468. } else if _, commit := stmt.(*parser.CommitStmt); commit {
  469. // A failed COMMIT has already rolled the transaction back in
  470. // storage; leaving the session in the failed state would make
  471. // every following statement (including ROLLBACK) fail.
  472. c.txStatus = TxStatusIdle
  473. } else if c.txStatus == TxStatusInBlock {
  474. c.txStatus = TxStatusFailed
  475. }
  476. c.sendError("ERROR", code, message)
  477. return c.sendReadyForQuery()
  478. }
  479. if err := c.sendResult(result, stmt, wireColumnTypes(result), nil); err != nil {
  480. return err
  481. }
  482. if result.LSN > 0 {
  483. if err := c.sendLSN(result.LSN); err != nil {
  484. return err
  485. }
  486. }
  487. if resetsPortals(stmt) {
  488. // Same rule as the extended path: a transaction end or a savepoint
  489. // rollback invalidates every open portal. sendReadyForQuery covers
  490. // the idle case; ROLLBACK TO SAVEPOINT keeps the block open and
  491. // needs this explicit clear.
  492. c.clearPortals()
  493. }
  494. }
  495. return c.sendReadyForQuery()
  496. }
  497. func (c *Connection) handleParse(msg *Message) error {
  498. if c.extendedFailed {
  499. return nil
  500. }
  501. name, pos, err := readCString(msg.Data, 0)
  502. if err != nil {
  503. return c.failExtended(ErrCodeProtocolViolation, err)
  504. }
  505. query, pos, err := readCString(msg.Data, pos)
  506. if err != nil || pos+2 > len(msg.Data) {
  507. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Parse message"))
  508. }
  509. count := int(binary.BigEndian.Uint16(msg.Data[pos : pos+2]))
  510. pos += 2
  511. if pos+count*4 != len(msg.Data) {
  512. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Parse parameter list"))
  513. }
  514. oids := make([]int32, count)
  515. for i := range oids {
  516. oids[i] = int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  517. pos += 4
  518. }
  519. if !isSingleStatementSQL(query) {
  520. return c.failExtended(ErrCodeSyntaxError, fmt.Errorf("prepared statements must contain one command"))
  521. }
  522. paramOIDs, err := c.negotiateParameterOIDs(query, oids)
  523. if err != nil {
  524. return c.failExtended(ErrCodeProgramLimitExceeded, err)
  525. }
  526. c.statements[name] = &preparedStatement{query: query, paramOIDs: paramOIDs}
  527. return c.writeMessage(MsgParseComplete, nil)
  528. }
  529. func (c *Connection) handleBind(msg *Message) error {
  530. if c.extendedFailed {
  531. return nil
  532. }
  533. portalName, pos, err := readCString(msg.Data, 0)
  534. if err != nil {
  535. return c.failExtended(ErrCodeProtocolViolation, err)
  536. }
  537. statementName, pos, err := readCString(msg.Data, pos)
  538. if err != nil {
  539. return c.failExtended(ErrCodeProtocolViolation, err)
  540. }
  541. statement, ok := c.statements[statementName]
  542. if !ok {
  543. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("prepared statement %q does not exist", statementName))
  544. }
  545. // Named portals cannot be replaced: PostgreSQL reports 42P03 and leaves the
  546. // existing portal in place. Only the unnamed portal is re-bound freely,
  547. // because the new Bind replaces it.
  548. if portalName != "" {
  549. if _, exists := c.portals[portalName]; exists {
  550. return c.failExtended(ErrCodeDuplicateCursor, fmt.Errorf("portal %q already exists", portalName))
  551. }
  552. }
  553. formats, pos, err := readInt16List(msg.Data, pos)
  554. if err != nil || pos+2 > len(msg.Data) {
  555. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind format list"))
  556. }
  557. paramCount := int(binary.BigEndian.Uint16(msg.Data[pos : pos+2]))
  558. pos += 2
  559. if len(formats) > 1 && len(formats) != paramCount {
  560. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("Bind parameter format count does not match parameters"))
  561. }
  562. for _, format := range formats {
  563. if format != 0 && format != 1 {
  564. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter format code"))
  565. }
  566. }
  567. params := make([]boundParameter, paramCount)
  568. for i := range params {
  569. if pos+4 > len(msg.Data) {
  570. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter"))
  571. }
  572. length := int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  573. pos += 4
  574. params[i].oid = parameterOID(statement.paramOIDs, i)
  575. params[i].format = parameterFormat(formats, i)
  576. if length == -1 {
  577. params[i].null = true
  578. continue
  579. }
  580. if length < 0 || pos+int(length) > len(msg.Data) {
  581. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter length"))
  582. }
  583. params[i].value = append([]byte(nil), msg.Data[pos:pos+int(length)]...)
  584. pos += int(length)
  585. }
  586. resultFormats, pos, err := readInt16List(msg.Data, pos)
  587. if err != nil || pos != len(msg.Data) {
  588. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind result format list"))
  589. }
  590. for _, format := range resultFormats {
  591. if format != 0 && format != 1 {
  592. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind result format code"))
  593. }
  594. }
  595. query, err := bindQuery(statement.query, params)
  596. if err != nil {
  597. code := ErrCodeInvalidParameter
  598. if errors.Is(err, pgerror.ErrFeatureNotSupported) {
  599. code = ErrCodeFeatureNotSupported
  600. }
  601. if errors.Is(err, pgerror.ErrInvalidText) {
  602. code = ErrCodeInvalidText
  603. }
  604. if errors.Is(err, pgerror.ErrInvalidParameter) {
  605. code = ErrCodeInvalidParameter
  606. }
  607. return c.failExtended(code, err)
  608. }
  609. c.portals[portalName] = &portal{query: query, resultFormats: resultFormats}
  610. return c.writeMessage(MsgBindComplete, nil)
  611. }
  612. func (c *Connection) handleDescribe(msg *Message) error {
  613. if c.extendedFailed {
  614. return nil
  615. }
  616. if len(msg.Data) < 2 {
  617. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe message"))
  618. }
  619. name, pos, err := readCString(msg.Data, 1)
  620. if err != nil || pos != len(msg.Data) {
  621. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe name"))
  622. }
  623. switch msg.Data[0] {
  624. case 'S':
  625. statement, ok := c.statements[name]
  626. if !ok {
  627. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("prepared statement %q does not exist", name))
  628. }
  629. if err := c.sendParameterDescription(statement.paramOIDs); err != nil {
  630. return err
  631. }
  632. case 'P':
  633. // PostgreSQL reports parameter types only for Describe('S'). Portal
  634. // Describe returns row metadata (here NoData) without a
  635. // ParameterDescription.
  636. if _, ok := c.portals[name]; !ok {
  637. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("portal %q does not exist", name))
  638. }
  639. default:
  640. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe target"))
  641. }
  642. // Row metadata requires analysis without side effects. Return NoData for
  643. // compatibility; Execute still emits the real RowDescription. This is the
  644. // pre-0.4.0 behavior used by common extended-protocol clients.
  645. return c.writeMessage(MsgNoData, nil)
  646. }
  647. func (c *Connection) handleExecute(msg *Message) error {
  648. if c.extendedFailed {
  649. return nil
  650. }
  651. name, pos, err := readCString(msg.Data, 0)
  652. if err != nil || pos+4 != len(msg.Data) {
  653. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Execute message"))
  654. }
  655. portal, ok := c.portals[name]
  656. if !ok {
  657. return c.failExtended(ErrCodeUndefinedCursor, fmt.Errorf("portal %q does not exist", name))
  658. }
  659. maxRows := int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  660. if maxRows < 0 {
  661. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Execute row limit: %d", maxRows))
  662. }
  663. // Check the transaction state before catalog emulation. Catalog queries do
  664. // not all parse as regular PizzaSQL statements, but must still return 25P02
  665. // while the transaction is aborted.
  666. if c.txStatus == TxStatusFailed && !isRollbackStatement(portal.query) {
  667. return c.failExtended(ErrCodeTransactionAborted, fmt.Errorf("current transaction is aborted, commands ignored until end of transaction block"))
  668. }
  669. if portal.execution == nil {
  670. if failure := c.materializePortal(portal); failure != nil {
  671. return c.failExtended(failure.code, failure.err)
  672. }
  673. }
  674. if err := c.sendPortalRows(portal, maxRows); err != nil {
  675. return err
  676. }
  677. if portal.execution.clearsPortals {
  678. c.clearPortals()
  679. }
  680. return nil
  681. }
  682. // executeError is a rejected Execute. Its transaction-state effects have already
  683. // been applied by the time it is built, so handleExecute only reports it.
  684. type executeError struct {
  685. code string
  686. err error
  687. }
  688. // materializePortal runs a portal's statement once and stores everything the
  689. // Execute responses need. The executor already produces a complete result, so a
  690. // resumed Execute stays a slice of that result and never runs the SQL again;
  691. // column metadata and the completion tag are also computed once. A nil return
  692. // means the portal is ready to stream.
  693. func (c *Connection) materializePortal(portal *portal) *executeError {
  694. execution := &portalExecution{}
  695. stmt, err := parser.New(lexer.New(portal.query)).Parse()
  696. if err != nil {
  697. code := ErrCodeSyntaxError
  698. if errors.Is(err, pgerror.ErrFeatureNotSupported) {
  699. code = ErrCodeFeatureNotSupported
  700. if c.txStatus == TxStatusInBlock {
  701. c.txStatus = TxStatusFailed
  702. }
  703. }
  704. return &executeError{code: code, err: fmt.Errorf("syntax error: %w", err)}
  705. }
  706. result, err := c.executor.Execute(stmt)
  707. if err != nil && isIdleRollback(stmt, c.txStatus, err) {
  708. result, err = executor.NewResult("ROLLBACK"), nil
  709. }
  710. if err != nil {
  711. return c.classifyExecuteError(stmt, err)
  712. }
  713. execution.result = result
  714. // getCommandTag applies the statement's transaction transition, so it
  715. // belongs here: a repeated Execute must not replay BEGIN/COMMIT/ROLLBACK.
  716. execution.commandTag = c.getCommandTag(stmt, result)
  717. execution.clearsPortals = resetsPortals(stmt)
  718. columnTypes := wireColumnTypes(execution.result)
  719. formats, formatErr := c.resolveResultFormats(portal.resultFormats, columnTypes, len(execution.result.Columns))
  720. if formatErr != nil {
  721. return &executeError{code: resultFormatSQLState(formatErr), err: formatErr}
  722. }
  723. execution.columnTypes = columnTypes
  724. execution.oids = c.resultColumnOIDs(columnTypes, len(execution.result.Columns))
  725. execution.formats = formats
  726. portal.execution = execution
  727. return nil
  728. }
  729. // classifyExecuteError maps a statement execution error to the SQLSTATE the
  730. // client receives and leaves the transaction state consistent.
  731. func (c *Connection) classifyExecuteError(stmt parser.Statement, err error) *executeError {
  732. code := ErrCodeInternalError
  733. var primaryKeyErr *storage.PrimaryKeyViolationError
  734. var uniqueErr *storage.UniqueViolationError
  735. var notNullErr *storage.NotNullViolationError
  736. var checkErr *storage.CheckViolationError
  737. var foreignKeyErr *storage.ForeignKeyViolationError
  738. if errors.Is(err, storage.ErrSerialization) {
  739. code = ErrCodeSerializationFailure
  740. c.txStatus = TxStatusIdle
  741. } else if errors.Is(err, pgerror.ErrInvalidText) {
  742. code = ErrCodeInvalidText
  743. if c.txStatus == TxStatusInBlock {
  744. c.txStatus = TxStatusFailed
  745. }
  746. } else if errors.Is(err, pgerror.ErrInvalidParameter) {
  747. code = ErrCodeInvalidParameter
  748. if c.txStatus == TxStatusInBlock {
  749. c.txStatus = TxStatusFailed
  750. }
  751. } else if errors.Is(err, pgerror.ErrDatatypeMismatch) {
  752. code = ErrCodeDatatypeMismatch
  753. if c.txStatus == TxStatusInBlock {
  754. c.txStatus = TxStatusFailed
  755. }
  756. } else if analysisTypeMismatch(err) {
  757. code = ErrCodeDatatypeMismatch
  758. if c.txStatus == TxStatusInBlock {
  759. c.txStatus = TxStatusFailed
  760. }
  761. } else if errors.As(err, &notNullErr) {
  762. code = "23502"
  763. if _, commit := stmt.(*parser.CommitStmt); commit {
  764. c.txStatus = TxStatusIdle
  765. } else if c.txStatus == TxStatusInBlock {
  766. c.txStatus = TxStatusFailed
  767. }
  768. } else if errors.As(err, &checkErr) {
  769. code = ErrCodeCheckViolation
  770. if _, commit := stmt.(*parser.CommitStmt); commit {
  771. c.txStatus = TxStatusIdle
  772. } else if c.txStatus == TxStatusInBlock {
  773. c.txStatus = TxStatusFailed
  774. }
  775. } else if errors.As(err, &foreignKeyErr) {
  776. code = ErrCodeForeignKeyViolation
  777. if _, commit := stmt.(*parser.CommitStmt); commit {
  778. c.txStatus = TxStatusIdle
  779. } else if c.txStatus == TxStatusInBlock {
  780. c.txStatus = TxStatusFailed
  781. }
  782. } else if errors.As(err, &uniqueErr) || errors.As(err, &primaryKeyErr) {
  783. code = ErrCodeUniqueViolation
  784. if _, commit := stmt.(*parser.CommitStmt); commit {
  785. c.txStatus = TxStatusIdle
  786. } else if c.txStatus == TxStatusInBlock {
  787. c.txStatus = TxStatusFailed
  788. }
  789. } else if errors.Is(err, pgerror.ErrFeatureNotSupported) || errors.Is(err, executor.ErrUnsupportedFeature) {
  790. code = ErrCodeFeatureNotSupported
  791. if c.txStatus == TxStatusInBlock {
  792. c.txStatus = TxStatusFailed
  793. }
  794. } else if _, commit := stmt.(*parser.CommitStmt); commit {
  795. c.txStatus = TxStatusIdle
  796. } else if c.txStatus == TxStatusInBlock {
  797. c.txStatus = TxStatusFailed
  798. }
  799. if uniqueErr != nil {
  800. return &executeError{code: code, err: fmt.Errorf("execution error: UNIQUE constraint failed: %s", uniqueErr.Constraint)}
  801. }
  802. return &executeError{code: code, err: fmt.Errorf("execution error: %w", err)}
  803. }
  804. // sendPortalRows writes one Execute response from the portal's materialized
  805. // result. The RowDescription is sent once, by the first Execute that has
  806. // columns, so a resumed Execute emits only DataRows. With maxRows > 0 the
  807. // response is PortalSuspended once the limit was reached; PostgreSQL reports
  808. // PortalSuspended even when the last row falls exactly on the limit and
  809. // completes on the next Execute, which is what this does too.
  810. func (c *Connection) sendPortalRows(portal *portal, maxRows int32) error {
  811. execution := portal.execution
  812. if len(execution.result.Columns) > 0 && !execution.described {
  813. if err := c.sendRowDescriptionFormats(execution.result.Columns, execution.columnTypes, execution.oids, execution.formats); err != nil {
  814. return err
  815. }
  816. execution.described = true
  817. }
  818. remaining := len(execution.result.Rows) - execution.rowOffset
  819. limit := remaining
  820. if maxRows > 0 && int(maxRows) < remaining {
  821. limit = int(maxRows)
  822. }
  823. for i := 0; i < limit; i++ {
  824. if err := c.sendDataRowFormats(execution.result.Rows[execution.rowOffset+i], execution.oids, execution.formats); err != nil {
  825. return c.failBinaryEncode(err)
  826. }
  827. }
  828. execution.rowOffset += limit
  829. if maxRows > 0 && limit == int(maxRows) {
  830. return c.sendPortalSuspended()
  831. }
  832. firstCompletion := !execution.completed
  833. execution.completed = true
  834. if err := c.sendCommandComplete(execution.commandTag); err != nil {
  835. return err
  836. }
  837. if firstCompletion && execution.result.LSN > 0 {
  838. if err := c.sendLSN(execution.result.LSN); err != nil {
  839. return err
  840. }
  841. }
  842. // The portal is exhausted: keep its metadata for a repeated Execute, but
  843. // release the row data so a transaction that leaves portals open does not
  844. // retain every result.
  845. execution.result.Rows = nil
  846. execution.rowOffset = 0
  847. return nil
  848. }
  849. func (c *Connection) sendTabularResult(result *executor.Result, tag string, bindFormats []int16) error {
  850. formats, err := c.resolveResultFormats(bindFormats, result.ColumnTypes, len(result.Columns))
  851. if err != nil {
  852. return c.failResultFormat(err)
  853. }
  854. oids := c.resultColumnOIDs(result.ColumnTypes, len(result.Columns))
  855. if err := c.sendRowDescriptionFormats(result.Columns, result.ColumnTypes, oids, formats); err != nil {
  856. return err
  857. }
  858. for _, row := range result.Rows {
  859. if err := c.sendDataRowFormats(row, oids, formats); err != nil {
  860. return c.failBinaryEncode(err)
  861. }
  862. }
  863. return c.sendCommandComplete(fmt.Sprintf("%s %d", tag, len(result.Rows)))
  864. }
  865. func (c *Connection) handleClose(msg *Message) error {
  866. if c.extendedFailed {
  867. return nil
  868. }
  869. if len(msg.Data) < 2 {
  870. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close message"))
  871. }
  872. name, pos, err := readCString(msg.Data, 1)
  873. if err != nil || pos != len(msg.Data) {
  874. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close name"))
  875. }
  876. if msg.Data[0] == 'S' {
  877. delete(c.statements, name)
  878. } else if msg.Data[0] == 'P' {
  879. delete(c.portals, name)
  880. } else {
  881. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close target"))
  882. }
  883. return c.writeMessage(MsgCloseComplete, nil)
  884. }
  885. // clearPortals drops every portal. PostgreSQL binds a portal to the transaction
  886. // that created it: Sync ends the implicit transaction outside an explicit
  887. // block, and COMMIT/ROLLBACK end an explicit one. Prepared statements are not
  888. // affected, so a client re-binds after the transaction ends.
  889. func (c *Connection) clearPortals() {
  890. clear(c.portals)
  891. }
  892. // resetsPortals reports whether stmt invalidates every open portal. COMMIT and
  893. // ROLLBACK end the transaction, and ROLLBACK TO SAVEPOINT undoes writes a
  894. // suspended portal may already have materialized: resuming it would stream rows
  895. // and a completion tag from a removed state. Clearing every portal on ROLLBACK
  896. // TO SAVEPOINT is stricter than PostgreSQL, which keeps portals created before
  897. // the savepoint; the coarse rule is what keeps a failed or rewound statement
  898. // from leaking into a resumed stream.
  899. func resetsPortals(stmt parser.Statement) bool {
  900. switch stmt.(type) {
  901. case *parser.CommitStmt, *parser.RollbackStmt:
  902. return true
  903. }
  904. return false
  905. }
  906. func (c *Connection) failExtended(code string, err error) error {
  907. c.extendedFailed = true
  908. if c.txStatus == TxStatusInBlock {
  909. c.txStatus = TxStatusFailed
  910. }
  911. return c.sendError("ERROR", code, err.Error())
  912. }
  913. func (c *Connection) handleProxyError(msg *Message) error {
  914. if len(msg.Data) != 1 || (msg.Data[0] != MsgQuery && msg.Data[0] != MsgParse) {
  915. _ = c.sendError("FATAL", ErrCodeProtocolViolation, "invalid proxy error relay")
  916. return io.EOF
  917. }
  918. code, message := "42501", "permission denied by API key scopes"
  919. if c.txStatus == TxStatusFailed {
  920. code, message = ErrCodeTransactionAborted, "current transaction is aborted, commands ignored until end of transaction block"
  921. }
  922. if msg.Data[0] == MsgParse {
  923. c.extendedCycle = true
  924. return c.failExtended(code, errors.New(message))
  925. }
  926. if c.txStatus == TxStatusInBlock {
  927. c.txStatus = TxStatusFailed
  928. }
  929. if err := c.sendError("ERROR", code, message); err != nil {
  930. return err
  931. }
  932. return c.sendReadyForQuery()
  933. }
  934. // analysisTypeMismatch reports whether the error is an analyzer type-mismatch,
  935. // which is reported with SQLSTATE 42804 instead of a generic internal error.
  936. func analysisTypeMismatch(err error) bool {
  937. var analysisErr *analyzer.AnalysisError
  938. return errors.As(err, &analysisErr) && analysisErr.Type == analyzer.ErrTypeMismatch
  939. }
  940. type boundParameter struct {
  941. value []byte
  942. oid int32
  943. format int16
  944. null bool
  945. }
  946. func readCString(data []byte, pos int) (string, int, error) {
  947. if pos < 0 || pos >= len(data) {
  948. return "", pos, fmt.Errorf("missing null-terminated string")
  949. }
  950. end := bytes.IndexByte(data[pos:], 0)
  951. if end < 0 {
  952. return "", pos, fmt.Errorf("unterminated string")
  953. }
  954. return string(data[pos : pos+end]), pos + end + 1, nil
  955. }
  956. func readInt16List(data []byte, pos int) ([]int16, int, error) {
  957. if pos+2 > len(data) {
  958. return nil, pos, fmt.Errorf("missing list length")
  959. }
  960. count := int(binary.BigEndian.Uint16(data[pos : pos+2]))
  961. pos += 2
  962. if pos+count*2 > len(data) {
  963. return nil, pos, fmt.Errorf("truncated list")
  964. }
  965. result := make([]int16, count)
  966. for i := range result {
  967. result[i] = int16(binary.BigEndian.Uint16(data[pos : pos+2]))
  968. pos += 2
  969. }
  970. return result, pos, nil
  971. }
  972. func parameterOID(oids []int32, index int) int32 {
  973. if index < len(oids) {
  974. return oids[index]
  975. }
  976. return 0
  977. }
  978. func parameterFormat(formats []int16, index int) int16 {
  979. if len(formats) == 1 {
  980. return formats[0]
  981. }
  982. if index < len(formats) {
  983. return formats[index]
  984. }
  985. return 0
  986. }
  987. func bindQuery(query string, params []boundParameter) (string, error) {
  988. var result strings.Builder
  989. last := 0
  990. for _, reference := range scanParameters(query) {
  991. result.WriteString(query[last:reference.start])
  992. if reference.number < 1 || reference.number > len(params) {
  993. return "", fmt.Errorf("parameter %s was not provided", query[reference.start:reference.end])
  994. }
  995. literal, err := parameterLiteral(params[reference.number-1])
  996. if err != nil {
  997. return "", fmt.Errorf("parameter $%d: %w", reference.number, err)
  998. }
  999. result.WriteString(literal)
  1000. last = reference.end
  1001. }
  1002. result.WriteString(query[last:])
  1003. return result.String(), nil
  1004. }
  1005. func parameterLiteral(param boundParameter) (string, error) {
  1006. if param.null {
  1007. return "NULL", nil
  1008. }
  1009. if param.format == 1 {
  1010. if element, isArray := arrayParamElementType(param.oid); isArray {
  1011. return binaryArrayLiteral(element, param.value)
  1012. }
  1013. if param.oid == 3802 {
  1014. // PostgreSQL's binary jsonb format is a version byte followed by the
  1015. // document text. pgx sends this form by default.
  1016. if len(param.value) == 0 {
  1017. return "", pgerror.InvalidText("jsonb binary parameter is empty")
  1018. }
  1019. if param.value[0] != 1 {
  1020. return "", pgerror.InvalidText("unsupported jsonb binary format version %d", param.value[0])
  1021. }
  1022. canonical, err := executor.CanonicalizeJSONB(string(param.value[1:]))
  1023. if err != nil {
  1024. return "", err
  1025. }
  1026. return "'" + strings.ReplaceAll(canonical, "'", "''") + "'::jsonb", nil
  1027. }
  1028. switch param.oid {
  1029. case 700, 701:
  1030. return binaryFloatText(param.oid, param.value)
  1031. case 1700:
  1032. return binaryNumericText(param.value)
  1033. case 16:
  1034. if len(param.value) != 1 || param.value[0] > 1 {
  1035. return "", pgerror.InvalidText("invalid binary boolean parameter")
  1036. }
  1037. if param.value[0] == 0 {
  1038. return "FALSE", nil
  1039. }
  1040. return "TRUE", nil
  1041. case 21:
  1042. if len(param.value) != 2 {
  1043. return "", fmt.Errorf("invalid binary int2")
  1044. }
  1045. return strconv.FormatInt(int64(int16(binary.BigEndian.Uint16(param.value))), 10), nil
  1046. case 23:
  1047. if len(param.value) != 4 {
  1048. return "", fmt.Errorf("invalid binary int4")
  1049. }
  1050. return strconv.FormatInt(int64(int32(binary.BigEndian.Uint32(param.value))), 10), nil
  1051. case 20:
  1052. if len(param.value) != 8 {
  1053. return "", fmt.Errorf("invalid binary int8")
  1054. }
  1055. return strconv.FormatInt(int64(binary.BigEndian.Uint64(param.value)), 10), nil
  1056. default:
  1057. return "", fmt.Errorf("%w: binary parameter format for OID %d", pgerror.ErrFeatureNotSupported, param.oid)
  1058. }
  1059. }
  1060. value := string(param.value)
  1061. if param.oid == 3802 {
  1062. // A text-format jsonb parameter is canonicalized at Bind, so the executor
  1063. // receives the same bytes a jsonb column stores and an invalid document
  1064. // fails before execution.
  1065. canonical, err := executor.CanonicalizeJSONB(value)
  1066. if err != nil {
  1067. return "", err
  1068. }
  1069. return "'" + strings.ReplaceAll(canonical, "'", "''") + "'::jsonb", nil
  1070. }
  1071. if element, isArray := arrayParamElementType(param.oid); isArray {
  1072. // The bound value is PostgreSQL array text. Validate and canonicalize it
  1073. // now so a malformed array fails at Bind instead of during row
  1074. // evaluation, then emit a typed literal the executor accepts unchanged.
  1075. arrayType := element + "[]"
  1076. canonical, err := executor.CanonicalizeArrayText(value, arrayType)
  1077. if err != nil {
  1078. return "", err
  1079. }
  1080. return "'" + strings.ReplaceAll(canonical, "'", "''") + "'::" + arrayType, nil
  1081. }
  1082. switch param.oid {
  1083. case 0:
  1084. if strings.EqualFold(value, "true") || strings.EqualFold(value, "false") {
  1085. return strings.ToUpper(value), nil
  1086. }
  1087. if _, err := strconv.ParseFloat(value, 64); err == nil && value != "" {
  1088. return value, nil
  1089. }
  1090. return "'" + strings.ReplaceAll(value, "'", "''") + "'", nil
  1091. case 16:
  1092. if strings.EqualFold(value, "true") || value == "1" || value == "t" {
  1093. return "TRUE", nil
  1094. }
  1095. return "FALSE", nil
  1096. case 20, 21, 23, 26, 700, 701, 1700:
  1097. if _, err := strconv.ParseFloat(value, 64); err != nil {
  1098. return "", fmt.Errorf("invalid numeric value")
  1099. }
  1100. return value, nil
  1101. default:
  1102. return "'" + strings.ReplaceAll(value, "'", "''") + "'", nil
  1103. }
  1104. }
  1105. // sendResult sends a statement's result. columnTypes are the types reported in
  1106. // RowDescription (already corrected for BLOB values) and formats are the
  1107. // portal's resolved per-column format codes, or nil for all-text results.
  1108. func (c *Connection) sendResult(result *executor.Result, stmt parser.Statement, columnTypes []string, formats []int16) error {
  1109. // Any statement that produced a row set (SELECT, or INSERT/UPDATE/DELETE
  1110. // with RETURNING) sends a row description and its data rows. Other
  1111. // statements only send the command completion tag.
  1112. if len(result.Columns) > 0 {
  1113. oids := c.resultColumnOIDs(columnTypes, len(result.Columns))
  1114. if err := c.sendRowDescriptionFormats(result.Columns, columnTypes, oids, formats); err != nil {
  1115. return err
  1116. }
  1117. for _, row := range result.Rows {
  1118. if err := c.sendDataRowFormats(row, oids, formats); err != nil {
  1119. return c.failBinaryEncode(err)
  1120. }
  1121. }
  1122. return c.sendCommandComplete(c.getCommandTag(stmt, result))
  1123. }
  1124. // For other statements, just send command complete
  1125. tag := c.getCommandTag(stmt, result)
  1126. return c.sendCommandComplete(tag)
  1127. }
  1128. // wireColumnTypes corrects declared-affinity metadata when SQLite has stored a
  1129. // value of another type. In particular, binding []byte to a VARCHAR column is
  1130. // still a BLOB in SQLite; advertising TEXT while encoding PostgreSQL bytea text
  1131. // would make clients receive the literal "\\x..." instead of the original
  1132. // bytes.
  1133. func wireColumnTypes(result *executor.Result) []string {
  1134. types := append([]string(nil), result.ColumnTypes...)
  1135. if len(types) < len(result.Columns) {
  1136. types = append(types, make([]string, len(result.Columns)-len(types))...)
  1137. }
  1138. for _, row := range result.Rows {
  1139. for i, value := range row {
  1140. if i >= len(types) {
  1141. break
  1142. }
  1143. if _, ok := value.([]byte); ok {
  1144. types[i] = "BLOB"
  1145. }
  1146. }
  1147. }
  1148. return types
  1149. }
  1150. // getCommandTag returns the command completion tag
  1151. func (c *Connection) getCommandTag(stmt parser.Statement, result *executor.Result) string {
  1152. switch s := stmt.(type) {
  1153. case *parser.SelectStmt:
  1154. return fmt.Sprintf("SELECT %d", len(result.Rows))
  1155. case *parser.CreateTableStmt:
  1156. return "CREATE TABLE"
  1157. case *parser.DropTableStmt:
  1158. return "DROP TABLE"
  1159. case *parser.CreateIndexStmt:
  1160. return "CREATE INDEX"
  1161. case *parser.DropIndexStmt:
  1162. return "DROP INDEX"
  1163. case *parser.AlterTableStmt:
  1164. return "ALTER TABLE"
  1165. case *parser.InsertStmt:
  1166. return fmt.Sprintf("INSERT 0 %d", result.RowsAffected)
  1167. case *parser.UpdateStmt:
  1168. return fmt.Sprintf("UPDATE %d", result.RowsAffected)
  1169. case *parser.DeleteStmt:
  1170. return fmt.Sprintf("DELETE %d", result.RowsAffected)
  1171. case *parser.BeginStmt:
  1172. c.txStatus = TxStatusInBlock
  1173. return "BEGIN"
  1174. case *parser.CommitStmt:
  1175. c.txStatus = TxStatusIdle
  1176. return "COMMIT"
  1177. case *parser.RollbackStmt:
  1178. if s.Savepoint != "" {
  1179. c.txStatus = TxStatusInBlock
  1180. return "ROLLBACK"
  1181. }
  1182. c.txStatus = TxStatusIdle
  1183. return "ROLLBACK"
  1184. case *parser.SavepointStmt:
  1185. c.txStatus = TxStatusInBlock
  1186. return "SAVEPOINT"
  1187. case *parser.ReleaseStmt:
  1188. c.txStatus = TxStatusInBlock
  1189. return "RELEASE"
  1190. case *parser.ListenStmt:
  1191. return "LISTEN"
  1192. case *parser.UnlistenStmt:
  1193. return "UNLISTEN"
  1194. case *parser.NotifyStmt:
  1195. return "NOTIFY"
  1196. default:
  1197. return "OK"
  1198. }
  1199. }
  1200. // sendAuthenticationOk sends authentication OK message
  1201. func (c *Connection) sendAuthenticationOk() error {
  1202. mb := NewMessageBuilder()
  1203. mb.WriteInt32(0) // Auth OK
  1204. return c.writeMessage(MsgAuthenticationOk, mb.Bytes())
  1205. }
  1206. // drainNotifications writes every notification currently buffered for this
  1207. // session. It is called at protocol-safe points (after Sync/ReadyForQuery).
  1208. func (c *Connection) drainNotifications() error {
  1209. ch := c.executor.NotificationChannel()
  1210. for {
  1211. select {
  1212. case n := <-ch:
  1213. if err := c.sendNotification(n); err != nil {
  1214. return err
  1215. }
  1216. default:
  1217. return c.writer.Flush()
  1218. }
  1219. }
  1220. }
  1221. // sendNotification writes a NotificationResponse frame. The frame is only
  1222. // written by the connection's main goroutine, never from a publisher.
  1223. func (c *Connection) sendNotification(n storage.Notification) error {
  1224. mb := NewMessageBuilder()
  1225. mb.WriteInt32(n.PID)
  1226. mb.WriteString(n.Channel)
  1227. mb.WriteString(n.Payload)
  1228. return c.writeMessage(MsgNotificationResponse, mb.Bytes())
  1229. }
  1230. // sendLSN exposes the last commit LSN as a ParameterStatus. Drivers that do
  1231. // not know the key ignore it; subscribers can use it as an ordering cursor.
  1232. func (c *Connection) sendLSN(lsn uint64) error {
  1233. return c.sendParameterStatus("pizzasql.lsn", strconv.FormatUint(lsn, 10))
  1234. }
  1235. // sendParameterStatus sends a parameter status message
  1236. func (c *Connection) sendParameterStatus(name, value string) error {
  1237. mb := NewMessageBuilder()
  1238. mb.WriteString(name)
  1239. mb.WriteString(value)
  1240. return c.writeMessage(MsgParameterStatus, mb.Bytes())
  1241. }
  1242. // sendBackendKeyData sends backend key data
  1243. func (c *Connection) sendBackendKeyData(processID, secretKey int32) error {
  1244. mb := NewMessageBuilder()
  1245. mb.WriteInt32(processID)
  1246. mb.WriteInt32(secretKey)
  1247. return c.writeMessage(MsgBackendKeyData, mb.Bytes())
  1248. }
  1249. // isIdleRollback reports whether a bare ROLLBACK found no transaction to roll
  1250. // back. A COMMIT rejected by storage has already ended the transaction, so the
  1251. // client's cleanup ROLLBACK must complete (PostgreSQL reports a warning and
  1252. // succeeds) instead of surfacing an internal error on an idle session.
  1253. func isIdleRollback(stmt parser.Statement, status byte, err error) bool {
  1254. rollback, ok := stmt.(*parser.RollbackStmt)
  1255. if !ok || rollback.Savepoint != "" {
  1256. return false
  1257. }
  1258. return status == TxStatusIdle && errors.Is(err, executor.ErrNoTransaction)
  1259. }
  1260. // sendReadyForQuery sends ready for query message
  1261. func (c *Connection) sendReadyForQuery() error {
  1262. if c.txStatus == TxStatusIdle {
  1263. // The transaction this cycle ran in ends here, so its portals do too.
  1264. // A portal inside an explicit block survives (status T) until
  1265. // COMMIT/ROLLBACK, and a failed block (status E) keeps its portals so
  1266. // Execute still reports 25P02 until the transaction is rolled back.
  1267. c.clearPortals()
  1268. }
  1269. mb := NewMessageBuilder()
  1270. mb.AppendByte(c.txStatus)
  1271. if err := c.writeMessage(MsgReadyForQuery, mb.Bytes()); err != nil {
  1272. return err
  1273. }
  1274. // ReadyForQuery closes out a response cycle, so flush everything buffered
  1275. // so far. This is what makes simple-query results and Sync responses
  1276. // visible to the client.
  1277. return c.writer.Flush()
  1278. }
  1279. // sendEmptyQueryResponse sends empty query response
  1280. func (c *Connection) sendEmptyQueryResponse() error {
  1281. return c.writeMessage(MsgEmptyQueryResponse, []byte{})
  1282. }
  1283. // sendParameterDescription reports the negotiated parameter types of a
  1284. // prepared statement. The protocol count field is 16-bit and the negotiated
  1285. // list never exceeds maxParameterNumber, so the conversion cannot lose a count.
  1286. func (c *Connection) sendParameterDescription(oids []int32) error {
  1287. if len(oids) > maxParameterNumber {
  1288. return fmt.Errorf("parameter description has %d entries; the protocol limit is %d", len(oids), maxParameterNumber)
  1289. }
  1290. mb := NewMessageBuilder()
  1291. mb.WriteInt16(int16(uint16(len(oids))))
  1292. for _, oid := range oids {
  1293. mb.WriteInt32(oid)
  1294. }
  1295. return c.writeMessage(MsgParameterDescription, mb.Bytes())
  1296. }
  1297. // sendRowDescription sends row description (column metadata) in text format.
  1298. func (c *Connection) sendRowDescription(columns []string, columnTypes []string) error {
  1299. return c.sendRowDescriptionFormats(columns, columnTypes, c.resultColumnOIDs(columnTypes, len(columns)), nil)
  1300. }
  1301. // sendRowDescriptionFormats sends row description with the per-column formats a
  1302. // portal resolved at Bind. PostgreSQL reports the bound formats in a portal
  1303. // RowDescription; this server emits its RowDescription at Execute instead of
  1304. // Describe, so the portal's formats travel with the row metadata. OIDs are the
  1305. // same for text and binary results.
  1306. func (c *Connection) sendRowDescriptionFormats(columns []string, columnTypes []string, oids []int32, formats []int16) error {
  1307. mb := NewMessageBuilder()
  1308. mb.WriteInt16(int16(len(columns)))
  1309. for i, col := range columns {
  1310. colType := typeNameAt(columnTypes, i)
  1311. format := int16(0)
  1312. if i < len(formats) {
  1313. format = formats[i]
  1314. }
  1315. mb.WriteString(col)
  1316. mb.WriteInt32(0) // table OID
  1317. mb.WriteInt16(0) // column attribute number
  1318. mb.WriteInt32(oids[i]) // type OID
  1319. mb.WriteInt16(c.getTypeSizeForType(colType)) // type size
  1320. mb.WriteInt32(-1) // type modifier
  1321. mb.WriteInt16(format) // format code
  1322. }
  1323. return c.writeMessage(MsgRowDescription, mb.Bytes())
  1324. }
  1325. // resultColumnOIDs returns the PostgreSQL OID reported for every result column.
  1326. func (c *Connection) resultColumnOIDs(columnTypes []string, columnCount int) []int32 {
  1327. oids := make([]int32, columnCount)
  1328. for i := range oids {
  1329. oids[i] = c.getOIDForType(typeNameAt(columnTypes, i))
  1330. }
  1331. return oids
  1332. }
  1333. // sendDataRow sends a data row in text format
  1334. func (c *Connection) sendDataRow(row []interface{}, columns []string) error {
  1335. return c.sendDataRowFormats(row, nil, nil)
  1336. }
  1337. // sendDataRowFormats sends one DataRow, choosing text or binary encoding per
  1338. // column from formats. NULL is always length -1. Binary values are appended
  1339. // directly into the DataRow buffer; a value that cannot be encoded fails before
  1340. // the row is written, so the client never receives a partial DataRow.
  1341. func (c *Connection) sendDataRowFormats(row []interface{}, oids []int32, formats []int16) error {
  1342. mb := NewMessageBuilder()
  1343. mb.WriteInt16(int16(len(row)))
  1344. for i, value := range row {
  1345. if value == nil {
  1346. mb.WriteInt32(-1) // NULL indicator
  1347. continue
  1348. }
  1349. format := int16(0)
  1350. if i < len(formats) {
  1351. format = formats[i]
  1352. }
  1353. if format == 0 {
  1354. strValue := c.valueToString(value)
  1355. mb.WriteInt32(int32(len(strValue)))
  1356. mb.WriteBytes([]byte(strValue))
  1357. continue
  1358. }
  1359. oid := int32(25) // TEXT, the fallback RowDescription OID
  1360. if i < len(oids) {
  1361. oid = oids[i]
  1362. }
  1363. err := mb.AppendBinary(func(dst []byte) ([]byte, error) {
  1364. return appendBinaryResultValue(dst, oid, value)
  1365. })
  1366. if err != nil {
  1367. return fmt.Errorf("binary result column %d: %w", i+1, err)
  1368. }
  1369. }
  1370. return c.writeMessage(MsgDataRow, mb.Bytes())
  1371. }
  1372. // sendCommandComplete sends command complete message
  1373. func (c *Connection) sendCommandComplete(tag string) error {
  1374. mb := NewMessageBuilder()
  1375. mb.WriteString(tag)
  1376. return c.writeMessage(MsgCommandComplete, mb.Bytes())
  1377. }
  1378. // sendPortalSuspended reports that a bounded Execute stopped at its row limit
  1379. // with rows left to fetch.
  1380. func (c *Connection) sendPortalSuspended() error {
  1381. return c.writeMessage(MsgPortalSuspended, nil)
  1382. }
  1383. // sendError sends an error response
  1384. func (c *Connection) sendError(severity, code, message string) error {
  1385. if severity == "ERROR" && c.txStatus == TxStatusInBlock {
  1386. c.txStatus = TxStatusFailed
  1387. }
  1388. mb := NewMessageBuilder()
  1389. mb.AppendByte(ErrorFieldSeverity)
  1390. mb.WriteString(severity)
  1391. mb.AppendByte(ErrorFieldCode)
  1392. mb.WriteString(code)
  1393. mb.AppendByte(ErrorFieldMessage)
  1394. mb.WriteString(message)
  1395. mb.AppendByte(0) // Terminator
  1396. if err := c.writeMessage(MsgErrorResponse, mb.Bytes()); err != nil {
  1397. return err
  1398. }
  1399. // Errors must be visible promptly, including FATAL startup failures that
  1400. // are not followed by a ReadyForQuery before the connection closes.
  1401. return c.writer.Flush()
  1402. }
  1403. // writeMessage buffers a message for the connection. It does not flush, so
  1404. // callers that need to make a response visible to the client must flush at the
  1405. // appropriate protocol boundary (ReadyForQuery, an explicit Flush message, or
  1406. // an error response). Buffering amortizes the per-message syscalls that a
  1407. // result set would otherwise incur; the underlying bufio.Writer bounds memory
  1408. // use so large result sets cannot grow the buffer without limit.
  1409. func (c *Connection) writeMessage(msgType byte, data []byte) error {
  1410. if !c.quiet {
  1411. log.Printf("Sending message type=%c length=%d", msgType, len(data)+4)
  1412. }
  1413. return WriteMessage(c.writer, msgType, data)
  1414. }
  1415. // arrayElementTypeName reports the element type of an array type name such as
  1416. // "INTEGER[]". It reports false for scalar type names.
  1417. func arrayElementTypeName(typeName string) (string, bool) {
  1418. upper := strings.ToUpper(strings.TrimSpace(typeName))
  1419. if !strings.HasSuffix(upper, "[]") {
  1420. return "", false
  1421. }
  1422. return strings.TrimSpace(strings.TrimSuffix(upper, "[]")), true
  1423. }
  1424. // arrayOIDForElement maps an array element type name to its PostgreSQL array
  1425. // OID. Narrower integer types report int8[] because values are not
  1426. // range-checked, matching the scalar carrier rule; NUMERIC reports numeric[]
  1427. // because array elements stay text.
  1428. func arrayOIDForElement(element string) int32 {
  1429. base := strings.ToUpper(strings.TrimSpace(element))
  1430. if idx := strings.IndexByte(base, '('); idx >= 0 {
  1431. base = strings.TrimSpace(base[:idx])
  1432. }
  1433. switch base {
  1434. case "INTEGER", "INT", "INT4":
  1435. return 1007 // INT4ARRAYOID
  1436. case "BIGINT", "INT8", "SMALLINT", "INT2", "TINYINT", "MEDIUMINT":
  1437. return 1016 // INT8ARRAYOID
  1438. case "BOOLEAN", "BOOL":
  1439. return 1000 // BOOLARRAYOID
  1440. case "REAL", "FLOAT", "FLOAT4":
  1441. return 1021 // FLOAT4ARRAYOID
  1442. case "DOUBLE", "DOUBLE PRECISION", "FLOAT8":
  1443. return 1022 // FLOAT8ARRAYOID
  1444. case "NUMERIC", "DECIMAL":
  1445. return 1231 // NUMERICARRAYOID
  1446. case "VARCHAR", "NVARCHAR", "CHARACTER VARYING":
  1447. return 1015 // VARCHARARRAYOID
  1448. default:
  1449. return 1009 // TEXTARRAYOID
  1450. }
  1451. }
  1452. // arrayParamElementType maps an array parameter OID to the element type the
  1453. // bound literal is cast to. Unknown OIDs are handled by callers.
  1454. func arrayParamElementType(oid int32) (string, bool) {
  1455. switch oid {
  1456. case 1009:
  1457. return "TEXT", true
  1458. case 1015:
  1459. return "VARCHAR", true
  1460. case 1007:
  1461. return "INTEGER", true
  1462. case 1016:
  1463. return "BIGINT", true
  1464. case 1005:
  1465. return "SMALLINT", true
  1466. case 1000:
  1467. return "BOOLEAN", true
  1468. case 1021:
  1469. return "REAL", true
  1470. case 1022:
  1471. return "DOUBLE", true
  1472. case 1231:
  1473. return "NUMERIC", true
  1474. default:
  1475. return "", false
  1476. }
  1477. }
  1478. // getOIDForType returns PostgreSQL OID for type.
  1479. //
  1480. // Types narrower than the value the engine carries are reported as the carrier
  1481. // type, because the engine does not range-check stored or cast values: a value
  1482. // that does not fit int2/int4 or float4 would fail client-side decoding rather
  1483. // than having been rejected on write. INTEGER and REAL keep their declared
  1484. // mappings, which predate this rule and are what existing clients expect.
  1485. func (c *Connection) getOIDForType(typeName string) int32 {
  1486. if element, ok := arrayElementTypeName(typeName); ok {
  1487. return arrayOIDForElement(element)
  1488. }
  1489. switch strings.ToUpper(typeName) {
  1490. case "SMALLINT", "INT2", "TINYINT", "MEDIUMINT":
  1491. // Carried as int64 and not range-checked, so int8 is the honest type.
  1492. return 20 // INT8OID
  1493. case "INTEGER", "INT", "INT4":
  1494. return 23 // INT4OID
  1495. case "BIGINT", "INT8":
  1496. return 20 // INT8OID
  1497. case "NUMERIC", "DECIMAL":
  1498. // Values round-trip through JSON as float64; there is no exact decimal
  1499. // carrier, so NUMERIC is not advertised.
  1500. return 701 // FLOAT8OID
  1501. case "JSONB":
  1502. return 3802 // JSONBOID
  1503. case "OID":
  1504. return 26 // OIDOID
  1505. case "REGCLASS":
  1506. return 2205 // REGCLASSOID
  1507. case "REGTYPE":
  1508. return 2206 // REGTYPEOID
  1509. case "NAME":
  1510. return 19 // NAMEOID
  1511. case "TEXT", "VARCHAR", "CHAR", "UUID":
  1512. // UUID is stored as text (SQLite-style), so it reports TEXTOID rather
  1513. // than the native PG UUID OID.
  1514. return 25 // TEXTOID
  1515. case "REAL", "FLOAT", "FLOAT4":
  1516. return 700 // FLOAT4OID
  1517. case "DOUBLE", "FLOAT8":
  1518. return 701 // FLOAT8OID
  1519. case "BOOLEAN", "BOOL":
  1520. return 16 // BOOLOID
  1521. case "BLOB":
  1522. return 17 // BYTEAOID
  1523. case "DATETIME", "TIMESTAMP":
  1524. // Datetime values are exchanged as UTC RFC3339 (ISO8601 with a timezone
  1525. // offset), which timestamptz decodes directly.
  1526. return 1184 // TIMESTAMPTZOID
  1527. case "DATE":
  1528. return 1082 // DATEOID
  1529. default:
  1530. return 25 // Default to TEXT
  1531. }
  1532. }
  1533. // getTypeSizeForType returns type size in bytes, or -1 for variable length.
  1534. func (c *Connection) getTypeSizeForType(typeName string) int16 {
  1535. if _, ok := arrayElementTypeName(typeName); ok {
  1536. return -1 // arrays are variable length
  1537. }
  1538. switch strings.ToUpper(typeName) {
  1539. case "SMALLINT", "INT2", "TINYINT", "MEDIUMINT":
  1540. return 8 // Reported as int8; see getOIDForType.
  1541. case "INTEGER", "INT", "INT4":
  1542. return 4
  1543. case "BIGINT", "INT8":
  1544. return 8
  1545. case "NUMERIC", "DECIMAL":
  1546. return 8 // Reported as float8; see getOIDForType.
  1547. case "REAL", "FLOAT", "FLOAT4":
  1548. return 4
  1549. case "DOUBLE", "FLOAT8":
  1550. return 8
  1551. case "BOOLEAN", "BOOL":
  1552. return 1
  1553. case "DATETIME", "TIMESTAMP":
  1554. return 8
  1555. case "DATE":
  1556. return 4
  1557. case "OID", "REGCLASS", "REGTYPE":
  1558. return 4
  1559. case "NAME":
  1560. return 64
  1561. default:
  1562. return -1 // Variable length
  1563. }
  1564. }
  1565. // valueToString converts a value to its PostgreSQL text representation
  1566. func (c *Connection) valueToString(value interface{}) string {
  1567. return textValueString(value)
  1568. }
  1569. // textValueString is the text representation the wire layer sends for a value.
  1570. // Binary text and bytea results reuse it so both formats carry the same bytes
  1571. // for values without a native binary form. PostgreSQL's text format for bytea is
  1572. // \x followed by hex, which lets libpq/pgx decode a BLOB column (OID 17)
  1573. // losslessly.
  1574. func textValueString(value interface{}) string {
  1575. if value == nil {
  1576. return ""
  1577. }
  1578. if b, ok := value.([]byte); ok {
  1579. return `\x` + hex.EncodeToString(b)
  1580. }
  1581. return fmt.Sprintf("%v", value)
  1582. }
  1583. // handleVersionQuery handles SELECT version()
  1584. func (c *Connection) handleVersionQuery() error {
  1585. columns := []string{"version"}
  1586. columnTypes := []string{"TEXT"}
  1587. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1588. return err
  1589. }
  1590. row := []interface{}{"PostgreSQL " + version.PostgreSQLCompatVersion + " (PizzaSQL)"}
  1591. if err := c.sendDataRow(row, columns); err != nil {
  1592. return err
  1593. }
  1594. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1595. return err
  1596. }
  1597. return c.sendReadyForQuery()
  1598. }
  1599. // handleCurrentUserQuery handles SELECT current_user
  1600. func (c *Connection) handleCurrentUserQuery() error {
  1601. columns := []string{"current_user"}
  1602. columnTypes := []string{"TEXT"}
  1603. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1604. return err
  1605. }
  1606. user := c.params["user"]
  1607. if user == "" {
  1608. user = "pizzasql"
  1609. }
  1610. row := []interface{}{user}
  1611. if err := c.sendDataRow(row, columns); err != nil {
  1612. return err
  1613. }
  1614. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1615. return err
  1616. }
  1617. return c.sendReadyForQuery()
  1618. }
  1619. // handleShowCommand handles SHOW commands
  1620. func (c *Connection) handleShowCommand(sqlUpper string) error {
  1621. var value string
  1622. var name string
  1623. if sqlUpper == "SERVER_VERSION" {
  1624. name = "server_version"
  1625. value = version.PostgreSQLCompatVersion
  1626. } else if sqlUpper == "SERVER_ENCODING" {
  1627. name = "server_encoding"
  1628. value = "UTF8"
  1629. } else if sqlUpper == "CLIENT_ENCODING" {
  1630. name = "client_encoding"
  1631. value = "UTF8"
  1632. } else {
  1633. // Unknown SHOW command
  1634. c.sendError("ERROR", ErrCodeFeatureNotSupported, "SHOW command not supported")
  1635. return c.sendReadyForQuery()
  1636. }
  1637. columns := []string{name}
  1638. columnTypes := []string{"TEXT"}
  1639. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1640. return err
  1641. }
  1642. row := []interface{}{value}
  1643. if err := c.sendDataRow(row, columns); err != nil {
  1644. return err
  1645. }
  1646. if err := c.sendCommandComplete("SHOW"); err != nil {
  1647. return err
  1648. }
  1649. return c.sendReadyForQuery()
  1650. }
  1651. // isRollbackStatement reports whether sql parses as a single ROLLBACK
  1652. // statement, including ROLLBACK TO SAVEPOINT.
  1653. func isRollbackStatement(sql string) bool {
  1654. stmt, err := parser.New(lexer.New(sql)).Parse()
  1655. if err != nil {
  1656. return false
  1657. }
  1658. _, ok := stmt.(*parser.RollbackStmt)
  1659. return ok
  1660. }