connection.go 46 KB

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