connection.go 43 KB

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