connection.go 43 KB

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