connection.go 59 KB

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