connection.go 48 KB

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