connection.go 43 KB

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