connection.go 47 KB

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