connection.go 42 KB

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