connection.go 49 KB

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