2
0

connection.go 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798
  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. "strconv"
  14. "strings"
  15. "sync/atomic"
  16. "github.com/danfragoso/pizzasql-next/pkg/analyzer"
  17. "github.com/danfragoso/pizzasql-next/pkg/executor"
  18. "github.com/danfragoso/pizzasql-next/pkg/lexer"
  19. "github.com/danfragoso/pizzasql-next/pkg/parser"
  20. "github.com/danfragoso/pizzasql-next/pkg/pgerror"
  21. "github.com/danfragoso/pizzasql-next/pkg/storage"
  22. "github.com/danfragoso/pizzasql-next/pkg/version"
  23. )
  24. // Connection represents a client connection
  25. type Connection struct {
  26. conn net.Conn
  27. reader *bufio.Reader
  28. writer *bufio.Writer
  29. executor *executor.Executor
  30. schema *storage.SchemaManager
  31. table *storage.TableManager
  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. // catalogFallback serves catalog emulation before the executor exists, when
  46. // a connection has managers but has not completed startup.
  47. catalogFallback *storage.Session
  48. }
  49. // backendPIDSeq gives each connection a distinct synthetic backend PID. It is
  50. // seeded with the process ID so NotificationResponse frames look plausible and
  51. // do not collide across server processes.
  52. var backendPIDSeq atomic.Int32
  53. func nextBackendPID() int32 {
  54. return int32(os.Getpid()) + backendPIDSeq.Add(1)
  55. }
  56. type preparedStatement struct {
  57. query string
  58. // paramOIDs is the negotiated parameter type list: the client's non-zero
  59. // Parse OIDs plus inferred types for the zeros. Describe reports it and
  60. // Bind decodes with it.
  61. paramOIDs []int32
  62. }
  63. // portal is one Bind result. Its lifetime follows PostgreSQL: a portal is
  64. // reusable until Close('P'), a Bind of the same name, or the end of the
  65. // transaction it was created in (see Connection.clearPortals).
  66. type portal struct {
  67. query string
  68. // resultFormats is the Bind result format list exactly as the client sent
  69. // it: empty (all text), one entry that repeats for every column, or one
  70. // entry per column. It is resolved once, when the first Execute produces the
  71. // result.
  72. resultFormats []int16
  73. // execution is nil until the first Execute. Materializing once lets a
  74. // resumed portal stream rows from execution.result instead of running the
  75. // statement again.
  76. execution *portalExecution
  77. }
  78. // portalExecution is the result a portal materialized on its first Execute,
  79. // plus the stream cursor a later Execute continues from.
  80. type portalExecution struct {
  81. result *executor.Result
  82. // columnTypes, oids, and formats are the result metadata resolved once for
  83. // every Execute of this portal.
  84. columnTypes []string
  85. oids []int32
  86. formats []int16
  87. // commandTag is the completion tag sent when the rows are exhausted.
  88. commandTag string
  89. // clearsPortals reports that this statement invalidated every open portal
  90. // (COMMIT, ROLLBACK, or ROLLBACK TO SAVEPOINT); see resetsPortals.
  91. clearsPortals bool
  92. rowOffset int
  93. // described is true once the RowDescription was sent, so a resumed Execute
  94. // sends only DataRows.
  95. described bool
  96. // completed is true once CommandComplete was sent; a further Execute
  97. // repeats the tag without re-running the statement.
  98. completed bool
  99. }
  100. // NewConnection creates a new connection handler
  101. func NewConnection(conn net.Conn, dbManager *storage.DatabaseManager, quiet bool) *Connection {
  102. return &Connection{
  103. conn: conn,
  104. reader: bufio.NewReader(conn),
  105. writer: bufio.NewWriter(conn),
  106. dbManager: dbManager,
  107. params: make(map[string]string),
  108. statements: make(map[string]*preparedStatement),
  109. portals: make(map[string]*portal),
  110. txStatus: TxStatusIdle,
  111. quiet: quiet,
  112. backendPID: nextBackendPID(),
  113. }
  114. }
  115. // Handle processes the connection
  116. func (c *Connection) Handle() error {
  117. defer func() {
  118. if c.executor != nil {
  119. if err := c.executor.Close(); err != nil && !c.quiet {
  120. log.Printf("failed to close session: %v", err)
  121. }
  122. }
  123. c.conn.Close()
  124. }()
  125. // First, check for SSL request (sent before startup message)
  126. // SSL request is 8 bytes: length(4) + code(4) where code = 80877103
  127. firstBytes := make([]byte, 8)
  128. n, err := io.ReadFull(c.reader, firstBytes)
  129. if err != nil {
  130. return fmt.Errorf("failed to read initial bytes: %w", err)
  131. }
  132. // Check if it's an SSL request (code 80877103 = 0x04D2162F)
  133. if n == 8 {
  134. length := binary.BigEndian.Uint32(firstBytes[0:4])
  135. code := binary.BigEndian.Uint32(firstBytes[4:8])
  136. if length == 8 && code == 80877103 {
  137. // SSL request - we don't support SSL, send 'N'
  138. if !c.quiet {
  139. log.Printf("Client requested SSL, sending rejection")
  140. }
  141. if _, err := c.conn.Write([]byte{'N'}); err != nil {
  142. return fmt.Errorf("failed to send SSL rejection: %w", err)
  143. }
  144. // Now read the actual startup message
  145. } else {
  146. // Not SSL request, this is part of startup message
  147. // We need to prepend these bytes back for ReadStartupMessage
  148. // Create a multi-reader that first reads our buffered bytes, then continues with the reader
  149. c.reader = bufio.NewReader(io.MultiReader(bytes.NewReader(firstBytes), c.reader))
  150. }
  151. }
  152. // Read startup message
  153. if !c.quiet {
  154. log.Printf("Reading startup message...")
  155. }
  156. params, err := ReadStartupMessage(c.reader)
  157. if err != nil {
  158. return fmt.Errorf("failed to read startup message: %w", err)
  159. }
  160. c.params = params
  161. if !c.quiet {
  162. log.Printf("Startup params: %+v", params)
  163. }
  164. // Get database name from params (default to "pizzasql")
  165. dbName := params["database"]
  166. if dbName == "" {
  167. dbName = "pizzasql"
  168. }
  169. c.database = dbName
  170. if !c.quiet {
  171. log.Printf("New connection: user=%s database=%s", params["user"], dbName)
  172. }
  173. // Initialize database
  174. if err := c.initDatabase(dbName); err != nil {
  175. c.sendError("FATAL", ErrCodeConnectionFailure, fmt.Sprintf("Failed to initialize database: %v", err))
  176. return err
  177. }
  178. // Send authentication OK (no auth for now)
  179. if err := c.sendAuthenticationOk(); err != nil {
  180. return err
  181. }
  182. // Send parameter status messages
  183. if err := c.sendParameterStatus("server_version", version.PostgreSQLCompatVersion+" (PizzaSQL)"); err != nil {
  184. return err
  185. }
  186. // Build identity is a separate, custom ParameterStatus so the PostgreSQL
  187. // compatibility string above stays stable for version-sniffing drivers.
  188. if err := c.sendParameterStatus("pizzasql.version", version.String()); err != nil {
  189. return err
  190. }
  191. if err := c.sendParameterStatus("pizzasql.commit", version.Commit); err != nil {
  192. return err
  193. }
  194. if err := c.sendParameterStatus("pizzasql.proxy_errors", "1"); err != nil {
  195. return err
  196. }
  197. if err := c.sendParameterStatus("server_encoding", "UTF8"); err != nil {
  198. return err
  199. }
  200. if err := c.sendParameterStatus("client_encoding", "UTF8"); err != nil {
  201. return err
  202. }
  203. if err := c.sendParameterStatus("DateStyle", "ISO, MDY"); err != nil {
  204. return err
  205. }
  206. if err := c.sendParameterStatus("TimeZone", "UTC"); err != nil {
  207. return err
  208. }
  209. // Send backend key data (for cancellation - we don't implement this yet)
  210. if err := c.sendBackendKeyData(c.backendPID, 67890); err != nil {
  211. return err
  212. }
  213. // Send ready for query
  214. if err := c.sendReadyForQuery(); err != nil {
  215. return err
  216. }
  217. // Read messages on a separate goroutine so an idle listener can receive
  218. // asynchronous NotificationResponse frames while blocked waiting for input.
  219. // Only this goroutine writes to c.writer, which keeps frame order intact.
  220. type readResult struct {
  221. msg *Message
  222. err error
  223. }
  224. inbox := make(chan readResult, 16)
  225. done := make(chan struct{})
  226. defer close(done)
  227. go func() {
  228. for {
  229. msg, err := ReadMessage(c.reader)
  230. select {
  231. case inbox <- readResult{msg: msg, err: err}:
  232. case <-done:
  233. return
  234. }
  235. if err != nil {
  236. return
  237. }
  238. }
  239. }()
  240. notifications := c.executor.NotificationChannel()
  241. overflow := c.executor.NotificationOverflow()
  242. for {
  243. // Do not interleave notifications into an extended-protocol cycle. The
  244. // channel is disabled until Sync closes the cycle.
  245. var notifyCh <-chan storage.Notification
  246. if !c.extendedCycle {
  247. notifyCh = notifications
  248. }
  249. select {
  250. case res := <-inbox:
  251. if res.err != nil {
  252. if res.err == io.EOF {
  253. log.Printf("Connection closed by client")
  254. return nil
  255. }
  256. return fmt.Errorf("failed to read message: %w", res.err)
  257. }
  258. switch res.msg.Type {
  259. case MsgParse, MsgBind, MsgDescribe, MsgExecute, MsgClose:
  260. c.extendedCycle = true
  261. }
  262. if err := c.handleMessage(res.msg); err != nil {
  263. if err == io.EOF {
  264. log.Printf("Connection closed normally")
  265. return nil
  266. }
  267. log.Printf("Error handling message: %v", err)
  268. return err
  269. }
  270. case n := <-notifyCh:
  271. if err := c.sendNotification(n); err != nil {
  272. return err
  273. }
  274. if err := c.writer.Flush(); err != nil {
  275. return err
  276. }
  277. case <-overflow:
  278. return fmt.Errorf("notification queue overflow: slow consumer disconnected")
  279. }
  280. }
  281. }
  282. // initDatabase initializes the database connection
  283. func (c *Connection) initDatabase(dbName string) error {
  284. db, err := c.dbManager.GetDatabase(dbName)
  285. if err != nil {
  286. return err
  287. }
  288. c.schema = db.Schema
  289. c.table = db.Table
  290. c.executor = executor.New(db.Schema, db.Table)
  291. c.executor.SetBackendPID(c.backendPID)
  292. c.executor.SetNotificationHub(db.Hub)
  293. c.executor.SyncCatalog()
  294. return nil
  295. }
  296. // handleMessage processes a client message
  297. func (c *Connection) handleMessage(msg *Message) error {
  298. if c.extendedFailed && msg.Type != MsgSync && msg.Type != MsgFlush && msg.Type != MsgTerminate {
  299. return nil
  300. }
  301. switch msg.Type {
  302. case MsgProxyError:
  303. return c.handleProxyError(msg)
  304. case MsgQuery:
  305. return c.handleQuery(msg)
  306. case MsgTerminate:
  307. log.Printf("Client requested termination")
  308. return io.EOF
  309. case MsgParse:
  310. return c.handleParse(msg)
  311. case MsgBind:
  312. return c.handleBind(msg)
  313. case MsgDescribe:
  314. return c.handleDescribe(msg)
  315. case MsgExecute:
  316. return c.handleExecute(msg)
  317. case MsgClose:
  318. return c.handleClose(msg)
  319. case MsgFlush:
  320. return c.writer.Flush()
  321. case MsgSync:
  322. c.extendedFailed = false
  323. c.extendedCycle = false
  324. if err := c.sendReadyForQuery(); err != nil {
  325. return err
  326. }
  327. return c.drainNotifications()
  328. default:
  329. log.Printf("Unknown message type: %c (%d)", msg.Type, msg.Type)
  330. c.sendError("ERROR", ErrCodeProtocolViolation, fmt.Sprintf("Unknown message type: %c", msg.Type))
  331. return c.sendReadyForQuery()
  332. }
  333. }
  334. // handleQuery processes a simple query
  335. func (c *Connection) handleQuery(msg *Message) error {
  336. // A Query message carries a single NUL-terminated query string.
  337. if len(msg.Data) == 0 || msg.Data[len(msg.Data)-1] != 0 {
  338. c.sendError("ERROR", ErrCodeProtocolViolation, "invalid Query message: missing null terminator")
  339. return c.sendReadyForQuery()
  340. }
  341. sql := string(msg.Data[:len(msg.Data)-1])
  342. if !c.quiet {
  343. log.Printf("Query: %s", sql)
  344. }
  345. // Handle empty query
  346. sqlTrimmed := strings.TrimSpace(sql)
  347. if sqlTrimmed == "" || sqlTrimmed == ";" {
  348. if err := c.sendEmptyQueryResponse(); err != nil {
  349. return err
  350. }
  351. return c.sendReadyForQuery()
  352. }
  353. // Handle special PostgreSQL system queries that drivers send
  354. singleStatement := isSingleStatementSQL(sql)
  355. // In a failed transaction only ROLLBACK (or ROLLBACK TO SAVEPOINT) is
  356. // accepted. Gate before honoring the special driver queries below so they
  357. // return 25P02 instead of a result. Multi-statement batches are gated
  358. // per statement in the execution loop below.
  359. if c.txStatus == TxStatusFailed && singleStatement && !isRollbackStatement(sql) {
  360. c.sendError("ERROR", ErrCodeTransactionAborted, "current transaction is aborted, commands ignored until end of transaction block")
  361. return c.sendReadyForQuery()
  362. }
  363. // Recognize only complete initialization-query token sequences.
  364. if singleStatement {
  365. switch kind := systemQueryKind(sql); kind {
  366. case "version":
  367. return c.handleVersionQuery()
  368. case "current_user":
  369. return c.handleCurrentUserQuery()
  370. case "server_version", "server_encoding", "client_encoding":
  371. return c.handleShowCommand(strings.ToUpper(kind))
  372. }
  373. }
  374. // Parse the complete batch before executing its first statement. This keeps
  375. // unsupported trailing clauses from turning into committed writes.
  376. l := lexer.New(sql)
  377. p := parser.New(l)
  378. stmts, err := p.ParseMultiple()
  379. if err != nil {
  380. code := ErrCodeSyntaxError
  381. if errors.Is(err, pgerror.ErrFeatureNotSupported) {
  382. code = ErrCodeFeatureNotSupported
  383. }
  384. if c.txStatus == TxStatusInBlock {
  385. c.txStatus = TxStatusFailed
  386. }
  387. c.sendError("ERROR", code, fmt.Sprintf("Syntax error: %v", err))
  388. return c.sendReadyForQuery()
  389. }
  390. for _, stmt := range stmts {
  391. if c.txStatus == TxStatusFailed {
  392. if _, rollback := stmt.(*parser.RollbackStmt); !rollback {
  393. c.sendError("ERROR", ErrCodeTransactionAborted, "current transaction is aborted, commands ignored until end of transaction block")
  394. return c.sendReadyForQuery()
  395. }
  396. }
  397. result, err := c.executor.Execute(stmt)
  398. if err != nil && isIdleRollback(stmt, c.txStatus, err) {
  399. result, err = executor.NewResult("ROLLBACK"), nil
  400. }
  401. if err != nil {
  402. code := ErrCodeInternalError
  403. message := fmt.Sprintf("Execution error: %v", err)
  404. var primaryKeyErr *storage.PrimaryKeyViolationError
  405. var uniqueErr *storage.UniqueViolationError
  406. var notNullErr *storage.NotNullViolationError
  407. var checkErr *storage.CheckViolationError
  408. var foreignKeyErr *storage.ForeignKeyViolationError
  409. if errors.Is(err, storage.ErrSerialization) {
  410. code = ErrCodeSerializationFailure
  411. c.txStatus = TxStatusIdle
  412. } else if errors.Is(err, pgerror.ErrInvalidText) {
  413. code = ErrCodeInvalidText
  414. if c.txStatus == TxStatusInBlock {
  415. c.txStatus = TxStatusFailed
  416. }
  417. } else if errors.Is(err, pgerror.ErrInvalidParameter) {
  418. code = ErrCodeInvalidParameter
  419. if c.txStatus == TxStatusInBlock {
  420. c.txStatus = TxStatusFailed
  421. }
  422. } else if errors.Is(err, pgerror.ErrDatatypeMismatch) {
  423. code = ErrCodeDatatypeMismatch
  424. if c.txStatus == TxStatusInBlock {
  425. c.txStatus = TxStatusFailed
  426. }
  427. } else if errors.Is(err, pgerror.ErrUndefinedTable) || analysisUndefinedTable(err) {
  428. code = ErrCodeUndefinedTable
  429. if c.txStatus == TxStatusInBlock {
  430. c.txStatus = TxStatusFailed
  431. }
  432. } else if analysisErr := analysisTypeMismatch(err); analysisErr {
  433. code = ErrCodeDatatypeMismatch
  434. if c.txStatus == TxStatusInBlock {
  435. c.txStatus = TxStatusFailed
  436. }
  437. } else if errors.As(err, &notNullErr) {
  438. code = "23502"
  439. if _, commit := stmt.(*parser.CommitStmt); commit {
  440. c.txStatus = TxStatusIdle
  441. } else if c.txStatus == TxStatusInBlock {
  442. c.txStatus = TxStatusFailed
  443. }
  444. } else if errors.As(err, &checkErr) {
  445. code = ErrCodeCheckViolation
  446. if _, commit := stmt.(*parser.CommitStmt); commit {
  447. c.txStatus = TxStatusIdle
  448. } else if c.txStatus == TxStatusInBlock {
  449. c.txStatus = TxStatusFailed
  450. }
  451. } else if errors.As(err, &foreignKeyErr) {
  452. code = ErrCodeForeignKeyViolation
  453. if _, commit := stmt.(*parser.CommitStmt); commit {
  454. c.txStatus = TxStatusIdle
  455. } else if c.txStatus == TxStatusInBlock {
  456. c.txStatus = TxStatusFailed
  457. }
  458. } else if errors.As(err, &uniqueErr) || errors.As(err, &primaryKeyErr) {
  459. code = ErrCodeUniqueViolation
  460. if uniqueErr != nil {
  461. message = fmt.Sprintf("Execution error: UNIQUE constraint failed: %s", uniqueErr.Constraint)
  462. }
  463. if _, commit := stmt.(*parser.CommitStmt); commit {
  464. c.txStatus = TxStatusIdle
  465. } else if c.txStatus == TxStatusInBlock {
  466. c.txStatus = TxStatusFailed
  467. }
  468. } else if errors.Is(err, pgerror.ErrFeatureNotSupported) || errors.Is(err, executor.ErrUnsupportedFeature) {
  469. code = ErrCodeFeatureNotSupported
  470. if c.txStatus == TxStatusInBlock {
  471. c.txStatus = TxStatusFailed
  472. }
  473. } else if _, commit := stmt.(*parser.CommitStmt); commit {
  474. // A failed COMMIT has already rolled the transaction back in
  475. // storage; leaving the session in the failed state would make
  476. // every following statement (including ROLLBACK) fail.
  477. c.txStatus = TxStatusIdle
  478. } else if c.txStatus == TxStatusInBlock {
  479. c.txStatus = TxStatusFailed
  480. }
  481. c.sendError("ERROR", code, message)
  482. return c.sendReadyForQuery()
  483. }
  484. if err := c.sendResult(result, stmt, wireColumnTypes(result), nil); err != nil {
  485. return err
  486. }
  487. if result.LSN > 0 {
  488. if err := c.sendLSN(result.LSN); err != nil {
  489. return err
  490. }
  491. }
  492. if resetsPortals(stmt) {
  493. // Same rule as the extended path: a transaction end or a savepoint
  494. // rollback invalidates every open portal. sendReadyForQuery covers
  495. // the idle case; ROLLBACK TO SAVEPOINT keeps the block open and
  496. // needs this explicit clear.
  497. c.clearPortals()
  498. }
  499. }
  500. return c.sendReadyForQuery()
  501. }
  502. func (c *Connection) handleParse(msg *Message) error {
  503. if c.extendedFailed {
  504. return nil
  505. }
  506. name, pos, err := readCString(msg.Data, 0)
  507. if err != nil {
  508. return c.failExtended(ErrCodeProtocolViolation, err)
  509. }
  510. query, pos, err := readCString(msg.Data, pos)
  511. if err != nil || pos+2 > len(msg.Data) {
  512. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Parse message"))
  513. }
  514. count := int(binary.BigEndian.Uint16(msg.Data[pos : pos+2]))
  515. pos += 2
  516. if pos+count*4 != len(msg.Data) {
  517. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Parse parameter list"))
  518. }
  519. oids := make([]int32, count)
  520. for i := range oids {
  521. oids[i] = int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  522. pos += 4
  523. }
  524. if !isSingleStatementSQL(query) {
  525. return c.failExtended(ErrCodeSyntaxError, fmt.Errorf("prepared statements must contain one command"))
  526. }
  527. paramOIDs, err := c.negotiateParameterOIDs(query, oids)
  528. if err != nil {
  529. return c.failExtended(ErrCodeProgramLimitExceeded, err)
  530. }
  531. c.statements[name] = &preparedStatement{query: query, paramOIDs: paramOIDs}
  532. return c.writeMessage(MsgParseComplete, nil)
  533. }
  534. func (c *Connection) handleBind(msg *Message) error {
  535. if c.extendedFailed {
  536. return nil
  537. }
  538. portalName, pos, err := readCString(msg.Data, 0)
  539. if err != nil {
  540. return c.failExtended(ErrCodeProtocolViolation, err)
  541. }
  542. statementName, pos, err := readCString(msg.Data, pos)
  543. if err != nil {
  544. return c.failExtended(ErrCodeProtocolViolation, err)
  545. }
  546. statement, ok := c.statements[statementName]
  547. if !ok {
  548. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("prepared statement %q does not exist", statementName))
  549. }
  550. // Named portals cannot be replaced: PostgreSQL reports 42P03 and leaves the
  551. // existing portal in place. Only the unnamed portal is re-bound freely,
  552. // because the new Bind replaces it.
  553. if portalName != "" {
  554. if _, exists := c.portals[portalName]; exists {
  555. return c.failExtended(ErrCodeDuplicateCursor, fmt.Errorf("portal %q already exists", portalName))
  556. }
  557. }
  558. formats, pos, err := readInt16List(msg.Data, pos)
  559. if err != nil || pos+2 > len(msg.Data) {
  560. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind format list"))
  561. }
  562. paramCount := int(binary.BigEndian.Uint16(msg.Data[pos : pos+2]))
  563. pos += 2
  564. if len(formats) > 1 && len(formats) != paramCount {
  565. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("Bind parameter format count does not match parameters"))
  566. }
  567. for _, format := range formats {
  568. if format != 0 && format != 1 {
  569. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter format code"))
  570. }
  571. }
  572. params := make([]boundParameter, paramCount)
  573. for i := range params {
  574. if pos+4 > len(msg.Data) {
  575. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter"))
  576. }
  577. length := int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  578. pos += 4
  579. params[i].oid = parameterOID(statement.paramOIDs, i)
  580. params[i].format = parameterFormat(formats, i)
  581. if length == -1 {
  582. params[i].null = true
  583. continue
  584. }
  585. if length < 0 || pos+int(length) > len(msg.Data) {
  586. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter length"))
  587. }
  588. params[i].value = append([]byte(nil), msg.Data[pos:pos+int(length)]...)
  589. pos += int(length)
  590. }
  591. resultFormats, pos, err := readInt16List(msg.Data, pos)
  592. if err != nil || pos != len(msg.Data) {
  593. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind result format list"))
  594. }
  595. for _, format := range resultFormats {
  596. if format != 0 && format != 1 {
  597. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind result format code"))
  598. }
  599. }
  600. query, err := bindQuery(statement.query, params)
  601. if err != nil {
  602. code := ErrCodeInvalidParameter
  603. if errors.Is(err, pgerror.ErrFeatureNotSupported) {
  604. code = ErrCodeFeatureNotSupported
  605. }
  606. if errors.Is(err, pgerror.ErrInvalidText) {
  607. code = ErrCodeInvalidText
  608. }
  609. if errors.Is(err, pgerror.ErrInvalidParameter) {
  610. code = ErrCodeInvalidParameter
  611. }
  612. return c.failExtended(code, err)
  613. }
  614. c.portals[portalName] = &portal{query: query, resultFormats: resultFormats}
  615. return c.writeMessage(MsgBindComplete, nil)
  616. }
  617. func (c *Connection) handleDescribe(msg *Message) error {
  618. if c.extendedFailed {
  619. return nil
  620. }
  621. if len(msg.Data) < 2 {
  622. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe message"))
  623. }
  624. name, pos, err := readCString(msg.Data, 1)
  625. if err != nil || pos != len(msg.Data) {
  626. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe name"))
  627. }
  628. switch msg.Data[0] {
  629. case 'S':
  630. statement, ok := c.statements[name]
  631. if !ok {
  632. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("prepared statement %q does not exist", name))
  633. }
  634. if err := c.sendParameterDescription(statement.paramOIDs); err != nil {
  635. return err
  636. }
  637. case 'P':
  638. // PostgreSQL reports parameter types only for Describe('S'). Portal
  639. // Describe returns row metadata (here NoData) without a
  640. // ParameterDescription.
  641. if _, ok := c.portals[name]; !ok {
  642. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("portal %q does not exist", name))
  643. }
  644. default:
  645. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe target"))
  646. }
  647. // Row metadata requires analysis without side effects. Return NoData for
  648. // compatibility; Execute still emits the real RowDescription. This is the
  649. // pre-0.4.0 behavior used by common extended-protocol clients.
  650. return c.writeMessage(MsgNoData, nil)
  651. }
  652. func (c *Connection) handleExecute(msg *Message) error {
  653. if c.extendedFailed {
  654. return nil
  655. }
  656. name, pos, err := readCString(msg.Data, 0)
  657. if err != nil || pos+4 != len(msg.Data) {
  658. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Execute message"))
  659. }
  660. portal, ok := c.portals[name]
  661. if !ok {
  662. return c.failExtended(ErrCodeUndefinedCursor, fmt.Errorf("portal %q does not exist", name))
  663. }
  664. maxRows := int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  665. if maxRows < 0 {
  666. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Execute row limit: %d", maxRows))
  667. }
  668. // Check the transaction state before catalog emulation. Catalog queries do
  669. // not all parse as regular PizzaSQL statements, but must still return 25P02
  670. // while the transaction is aborted.
  671. if c.txStatus == TxStatusFailed && !isRollbackStatement(portal.query) {
  672. return c.failExtended(ErrCodeTransactionAborted, fmt.Errorf("current transaction is aborted, commands ignored until end of transaction block"))
  673. }
  674. if portal.execution == nil {
  675. if failure := c.materializePortal(portal); failure != nil {
  676. return c.failExtended(failure.code, failure.err)
  677. }
  678. }
  679. if err := c.sendPortalRows(portal, maxRows); err != nil {
  680. return err
  681. }
  682. if portal.execution.clearsPortals {
  683. c.clearPortals()
  684. }
  685. return nil
  686. }
  687. // executeError is a rejected Execute. Its transaction-state effects have already
  688. // been applied by the time it is built, so handleExecute only reports it.
  689. type executeError struct {
  690. code string
  691. err error
  692. }
  693. // materializePortal runs a portal's statement once and stores everything the
  694. // Execute responses need. The executor already produces a complete result, so a
  695. // resumed Execute stays a slice of that result and never runs the SQL again;
  696. // column metadata and the completion tag are also computed once. A nil return
  697. // means the portal is ready to stream.
  698. func (c *Connection) materializePortal(portal *portal) *executeError {
  699. execution := &portalExecution{}
  700. stmt, err := parser.New(lexer.New(portal.query)).Parse()
  701. if err != nil {
  702. code := ErrCodeSyntaxError
  703. if errors.Is(err, pgerror.ErrFeatureNotSupported) {
  704. code = ErrCodeFeatureNotSupported
  705. if c.txStatus == TxStatusInBlock {
  706. c.txStatus = TxStatusFailed
  707. }
  708. }
  709. return &executeError{code: code, err: fmt.Errorf("syntax error: %w", err)}
  710. }
  711. result, err := c.executor.Execute(stmt)
  712. if err != nil && isIdleRollback(stmt, c.txStatus, err) {
  713. result, err = executor.NewResult("ROLLBACK"), nil
  714. }
  715. if err != nil {
  716. return c.classifyExecuteError(stmt, err)
  717. }
  718. execution.result = result
  719. // getCommandTag applies the statement's transaction transition, so it
  720. // belongs here: a repeated Execute must not replay BEGIN/COMMIT/ROLLBACK.
  721. execution.commandTag = c.getCommandTag(stmt, result)
  722. execution.clearsPortals = resetsPortals(stmt)
  723. columnTypes := wireColumnTypes(execution.result)
  724. formats, formatErr := c.resolveResultFormats(portal.resultFormats, columnTypes, len(execution.result.Columns))
  725. if formatErr != nil {
  726. return &executeError{code: resultFormatSQLState(formatErr), err: formatErr}
  727. }
  728. execution.columnTypes = columnTypes
  729. execution.oids = c.resultColumnOIDs(columnTypes, len(execution.result.Columns))
  730. execution.formats = formats
  731. portal.execution = execution
  732. return nil
  733. }
  734. // classifyExecuteError maps a statement execution error to the SQLSTATE the
  735. // client receives and leaves the transaction state consistent.
  736. func (c *Connection) classifyExecuteError(stmt parser.Statement, err error) *executeError {
  737. code := ErrCodeInternalError
  738. var primaryKeyErr *storage.PrimaryKeyViolationError
  739. var uniqueErr *storage.UniqueViolationError
  740. var notNullErr *storage.NotNullViolationError
  741. var checkErr *storage.CheckViolationError
  742. var foreignKeyErr *storage.ForeignKeyViolationError
  743. if errors.Is(err, storage.ErrSerialization) {
  744. code = ErrCodeSerializationFailure
  745. c.txStatus = TxStatusIdle
  746. } else if errors.Is(err, pgerror.ErrInvalidText) {
  747. code = ErrCodeInvalidText
  748. if c.txStatus == TxStatusInBlock {
  749. c.txStatus = TxStatusFailed
  750. }
  751. } else if errors.Is(err, pgerror.ErrInvalidParameter) {
  752. code = ErrCodeInvalidParameter
  753. if c.txStatus == TxStatusInBlock {
  754. c.txStatus = TxStatusFailed
  755. }
  756. } else if errors.Is(err, pgerror.ErrDatatypeMismatch) {
  757. code = ErrCodeDatatypeMismatch
  758. if c.txStatus == TxStatusInBlock {
  759. c.txStatus = TxStatusFailed
  760. }
  761. } else if errors.Is(err, pgerror.ErrUndefinedTable) || analysisUndefinedTable(err) {
  762. code = ErrCodeUndefinedTable
  763. if c.txStatus == TxStatusInBlock {
  764. c.txStatus = TxStatusFailed
  765. }
  766. } else if analysisTypeMismatch(err) {
  767. code = ErrCodeDatatypeMismatch
  768. if c.txStatus == TxStatusInBlock {
  769. c.txStatus = TxStatusFailed
  770. }
  771. } else if errors.As(err, &notNullErr) {
  772. code = "23502"
  773. if _, commit := stmt.(*parser.CommitStmt); commit {
  774. c.txStatus = TxStatusIdle
  775. } else if c.txStatus == TxStatusInBlock {
  776. c.txStatus = TxStatusFailed
  777. }
  778. } else if errors.As(err, &checkErr) {
  779. code = ErrCodeCheckViolation
  780. if _, commit := stmt.(*parser.CommitStmt); commit {
  781. c.txStatus = TxStatusIdle
  782. } else if c.txStatus == TxStatusInBlock {
  783. c.txStatus = TxStatusFailed
  784. }
  785. } else if errors.As(err, &foreignKeyErr) {
  786. code = ErrCodeForeignKeyViolation
  787. if _, commit := stmt.(*parser.CommitStmt); commit {
  788. c.txStatus = TxStatusIdle
  789. } else if c.txStatus == TxStatusInBlock {
  790. c.txStatus = TxStatusFailed
  791. }
  792. } else if errors.As(err, &uniqueErr) || errors.As(err, &primaryKeyErr) {
  793. code = ErrCodeUniqueViolation
  794. if _, commit := stmt.(*parser.CommitStmt); commit {
  795. c.txStatus = TxStatusIdle
  796. } else if c.txStatus == TxStatusInBlock {
  797. c.txStatus = TxStatusFailed
  798. }
  799. } else if errors.Is(err, pgerror.ErrFeatureNotSupported) || errors.Is(err, executor.ErrUnsupportedFeature) {
  800. code = ErrCodeFeatureNotSupported
  801. if c.txStatus == TxStatusInBlock {
  802. c.txStatus = TxStatusFailed
  803. }
  804. } else if _, commit := stmt.(*parser.CommitStmt); commit {
  805. c.txStatus = TxStatusIdle
  806. } else if c.txStatus == TxStatusInBlock {
  807. c.txStatus = TxStatusFailed
  808. }
  809. if uniqueErr != nil {
  810. return &executeError{code: code, err: fmt.Errorf("execution error: UNIQUE constraint failed: %s", uniqueErr.Constraint)}
  811. }
  812. return &executeError{code: code, err: fmt.Errorf("execution error: %w", err)}
  813. }
  814. // sendPortalRows writes one Execute response from the portal's materialized
  815. // result. The RowDescription is sent once, by the first Execute that has
  816. // columns, so a resumed Execute emits only DataRows. With maxRows > 0 the
  817. // response is PortalSuspended once the limit was reached; PostgreSQL reports
  818. // PortalSuspended even when the last row falls exactly on the limit and
  819. // completes on the next Execute, which is what this does too.
  820. func (c *Connection) sendPortalRows(portal *portal, maxRows int32) error {
  821. execution := portal.execution
  822. if len(execution.result.Columns) > 0 && !execution.described {
  823. if err := c.sendRowDescriptionFormats(execution.result.Columns, execution.columnTypes, execution.oids, execution.formats); err != nil {
  824. return err
  825. }
  826. execution.described = true
  827. }
  828. remaining := len(execution.result.Rows) - execution.rowOffset
  829. limit := remaining
  830. if maxRows > 0 && int(maxRows) < remaining {
  831. limit = int(maxRows)
  832. }
  833. for i := 0; i < limit; i++ {
  834. if err := c.sendDataRowFormats(execution.result.Rows[execution.rowOffset+i], execution.oids, execution.formats); err != nil {
  835. return c.failBinaryEncode(err)
  836. }
  837. }
  838. execution.rowOffset += limit
  839. if maxRows > 0 && limit == int(maxRows) {
  840. return c.sendPortalSuspended()
  841. }
  842. firstCompletion := !execution.completed
  843. execution.completed = true
  844. if err := c.sendCommandComplete(execution.commandTag); err != nil {
  845. return err
  846. }
  847. if firstCompletion && execution.result.LSN > 0 {
  848. if err := c.sendLSN(execution.result.LSN); err != nil {
  849. return err
  850. }
  851. }
  852. // The portal is exhausted: keep its metadata for a repeated Execute, but
  853. // release the row data so a transaction that leaves portals open does not
  854. // retain every result.
  855. execution.result.Rows = nil
  856. execution.rowOffset = 0
  857. return nil
  858. }
  859. func (c *Connection) sendTabularResult(result *executor.Result, tag string, bindFormats []int16) error {
  860. formats, err := c.resolveResultFormats(bindFormats, result.ColumnTypes, len(result.Columns))
  861. if err != nil {
  862. return c.failResultFormat(err)
  863. }
  864. oids := c.resultColumnOIDs(result.ColumnTypes, len(result.Columns))
  865. if err := c.sendRowDescriptionFormats(result.Columns, result.ColumnTypes, oids, formats); err != nil {
  866. return err
  867. }
  868. for _, row := range result.Rows {
  869. if err := c.sendDataRowFormats(row, oids, formats); err != nil {
  870. return c.failBinaryEncode(err)
  871. }
  872. }
  873. return c.sendCommandComplete(fmt.Sprintf("%s %d", tag, len(result.Rows)))
  874. }
  875. func (c *Connection) handleClose(msg *Message) error {
  876. if c.extendedFailed {
  877. return nil
  878. }
  879. if len(msg.Data) < 2 {
  880. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close message"))
  881. }
  882. name, pos, err := readCString(msg.Data, 1)
  883. if err != nil || pos != len(msg.Data) {
  884. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close name"))
  885. }
  886. if msg.Data[0] == 'S' {
  887. delete(c.statements, name)
  888. } else if msg.Data[0] == 'P' {
  889. delete(c.portals, name)
  890. } else {
  891. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close target"))
  892. }
  893. return c.writeMessage(MsgCloseComplete, nil)
  894. }
  895. // clearPortals drops every portal. PostgreSQL binds a portal to the transaction
  896. // that created it: Sync ends the implicit transaction outside an explicit
  897. // block, and COMMIT/ROLLBACK end an explicit one. Prepared statements are not
  898. // affected, so a client re-binds after the transaction ends.
  899. func (c *Connection) clearPortals() {
  900. clear(c.portals)
  901. }
  902. // resetsPortals reports whether stmt invalidates every open portal. COMMIT and
  903. // ROLLBACK end the transaction, and ROLLBACK TO SAVEPOINT undoes writes a
  904. // suspended portal may already have materialized: resuming it would stream rows
  905. // and a completion tag from a removed state. Clearing every portal on ROLLBACK
  906. // TO SAVEPOINT is stricter than PostgreSQL, which keeps portals created before
  907. // the savepoint; the coarse rule is what keeps a failed or rewound statement
  908. // from leaking into a resumed stream.
  909. func resetsPortals(stmt parser.Statement) bool {
  910. switch stmt.(type) {
  911. case *parser.CommitStmt, *parser.RollbackStmt:
  912. return true
  913. }
  914. return false
  915. }
  916. func (c *Connection) failExtended(code string, err error) error {
  917. c.extendedFailed = true
  918. if c.txStatus == TxStatusInBlock {
  919. c.txStatus = TxStatusFailed
  920. }
  921. return c.sendError("ERROR", code, err.Error())
  922. }
  923. func (c *Connection) handleProxyError(msg *Message) error {
  924. if len(msg.Data) != 1 || (msg.Data[0] != MsgQuery && msg.Data[0] != MsgParse) {
  925. _ = c.sendError("FATAL", ErrCodeProtocolViolation, "invalid proxy error relay")
  926. return io.EOF
  927. }
  928. code, message := "42501", "permission denied by API key scopes"
  929. if c.txStatus == TxStatusFailed {
  930. code, message = ErrCodeTransactionAborted, "current transaction is aborted, commands ignored until end of transaction block"
  931. }
  932. if msg.Data[0] == MsgParse {
  933. c.extendedCycle = true
  934. return c.failExtended(code, errors.New(message))
  935. }
  936. if c.txStatus == TxStatusInBlock {
  937. c.txStatus = TxStatusFailed
  938. }
  939. if err := c.sendError("ERROR", code, message); err != nil {
  940. return err
  941. }
  942. return c.sendReadyForQuery()
  943. }
  944. // analysisTypeMismatch reports whether the error is an analyzer type-mismatch,
  945. // which is reported with SQLSTATE 42804 instead of a generic internal error.
  946. func analysisTypeMismatch(err error) bool {
  947. var analysisErr *analyzer.AnalysisError
  948. return errors.As(err, &analysisErr) && analysisErr.Type == analyzer.ErrTypeMismatch
  949. }
  950. // analysisUndefinedTable reports whether the error is the analyzer's
  951. // table-not-found, which PostgreSQL reports as 42P01 (undefined_table).
  952. func analysisUndefinedTable(err error) bool {
  953. var analysisErr *analyzer.AnalysisError
  954. return errors.As(err, &analysisErr) && analysisErr.Type == analyzer.ErrTableNotFound
  955. }
  956. type boundParameter struct {
  957. value []byte
  958. oid int32
  959. format int16
  960. null bool
  961. }
  962. func readCString(data []byte, pos int) (string, int, error) {
  963. if pos < 0 || pos >= len(data) {
  964. return "", pos, fmt.Errorf("missing null-terminated string")
  965. }
  966. end := bytes.IndexByte(data[pos:], 0)
  967. if end < 0 {
  968. return "", pos, fmt.Errorf("unterminated string")
  969. }
  970. return string(data[pos : pos+end]), pos + end + 1, nil
  971. }
  972. func readInt16List(data []byte, pos int) ([]int16, int, error) {
  973. if pos+2 > len(data) {
  974. return nil, pos, fmt.Errorf("missing list length")
  975. }
  976. count := int(binary.BigEndian.Uint16(data[pos : pos+2]))
  977. pos += 2
  978. if pos+count*2 > len(data) {
  979. return nil, pos, fmt.Errorf("truncated list")
  980. }
  981. result := make([]int16, count)
  982. for i := range result {
  983. result[i] = int16(binary.BigEndian.Uint16(data[pos : pos+2]))
  984. pos += 2
  985. }
  986. return result, pos, nil
  987. }
  988. func parameterOID(oids []int32, index int) int32 {
  989. if index < len(oids) {
  990. return oids[index]
  991. }
  992. return 0
  993. }
  994. func parameterFormat(formats []int16, index int) int16 {
  995. if len(formats) == 1 {
  996. return formats[0]
  997. }
  998. if index < len(formats) {
  999. return formats[index]
  1000. }
  1001. return 0
  1002. }
  1003. func bindQuery(query string, params []boundParameter) (string, error) {
  1004. var result strings.Builder
  1005. last := 0
  1006. for _, reference := range scanParameters(query) {
  1007. result.WriteString(query[last:reference.start])
  1008. if reference.number < 1 || reference.number > len(params) {
  1009. return "", fmt.Errorf("parameter %s was not provided", query[reference.start:reference.end])
  1010. }
  1011. literal, err := parameterLiteral(params[reference.number-1])
  1012. if err != nil {
  1013. return "", fmt.Errorf("parameter $%d: %w", reference.number, err)
  1014. }
  1015. result.WriteString(literal)
  1016. last = reference.end
  1017. }
  1018. result.WriteString(query[last:])
  1019. return result.String(), nil
  1020. }
  1021. func parameterLiteral(param boundParameter) (string, error) {
  1022. if param.null {
  1023. return "NULL", nil
  1024. }
  1025. if param.format == 1 {
  1026. if element, isArray := arrayParamElementType(param.oid); isArray {
  1027. return binaryArrayLiteral(element, param.value)
  1028. }
  1029. if param.oid == 3802 {
  1030. // PostgreSQL's binary jsonb format is a version byte followed by the
  1031. // document text. pgx sends this form by default.
  1032. if len(param.value) == 0 {
  1033. return "", pgerror.InvalidText("jsonb binary parameter is empty")
  1034. }
  1035. if param.value[0] != 1 {
  1036. return "", pgerror.InvalidText("unsupported jsonb binary format version %d", param.value[0])
  1037. }
  1038. canonical, err := executor.CanonicalizeJSONB(string(param.value[1:]))
  1039. if err != nil {
  1040. return "", err
  1041. }
  1042. return "'" + strings.ReplaceAll(canonical, "'", "''") + "'::jsonb", nil
  1043. }
  1044. switch param.oid {
  1045. case 700, 701:
  1046. return binaryFloatText(param.oid, param.value)
  1047. case 1700:
  1048. return binaryNumericText(param.value)
  1049. case 16:
  1050. if len(param.value) != 1 || param.value[0] > 1 {
  1051. return "", pgerror.InvalidText("invalid binary boolean parameter")
  1052. }
  1053. if param.value[0] == 0 {
  1054. return "FALSE", nil
  1055. }
  1056. return "TRUE", nil
  1057. case 21:
  1058. if len(param.value) != 2 {
  1059. return "", fmt.Errorf("invalid binary int2")
  1060. }
  1061. return strconv.FormatInt(int64(int16(binary.BigEndian.Uint16(param.value))), 10), nil
  1062. case 23:
  1063. if len(param.value) != 4 {
  1064. return "", fmt.Errorf("invalid binary int4")
  1065. }
  1066. return strconv.FormatInt(int64(int32(binary.BigEndian.Uint32(param.value))), 10), nil
  1067. case 20:
  1068. if len(param.value) != 8 {
  1069. return "", fmt.Errorf("invalid binary int8")
  1070. }
  1071. return strconv.FormatInt(int64(binary.BigEndian.Uint64(param.value)), 10), nil
  1072. default:
  1073. return "", fmt.Errorf("%w: binary parameter format for OID %d", pgerror.ErrFeatureNotSupported, param.oid)
  1074. }
  1075. }
  1076. value := string(param.value)
  1077. if param.oid == 3802 {
  1078. // A text-format jsonb parameter is canonicalized at Bind, so the executor
  1079. // receives the same bytes a jsonb column stores and an invalid document
  1080. // fails before execution.
  1081. canonical, err := executor.CanonicalizeJSONB(value)
  1082. if err != nil {
  1083. return "", err
  1084. }
  1085. return "'" + strings.ReplaceAll(canonical, "'", "''") + "'::jsonb", nil
  1086. }
  1087. if element, isArray := arrayParamElementType(param.oid); isArray {
  1088. // The bound value is PostgreSQL array text. Validate and canonicalize it
  1089. // now so a malformed array fails at Bind instead of during row
  1090. // evaluation, then emit a typed literal the executor accepts unchanged.
  1091. arrayType := element + "[]"
  1092. canonical, err := executor.CanonicalizeArrayText(value, arrayType)
  1093. if err != nil {
  1094. return "", err
  1095. }
  1096. return "'" + strings.ReplaceAll(canonical, "'", "''") + "'::" + arrayType, nil
  1097. }
  1098. switch param.oid {
  1099. case 0:
  1100. if strings.EqualFold(value, "true") || strings.EqualFold(value, "false") {
  1101. return strings.ToUpper(value), nil
  1102. }
  1103. if _, err := strconv.ParseFloat(value, 64); err == nil && value != "" {
  1104. return value, nil
  1105. }
  1106. return "'" + strings.ReplaceAll(value, "'", "''") + "'", nil
  1107. case 16:
  1108. if strings.EqualFold(value, "true") || value == "1" || value == "t" {
  1109. return "TRUE", nil
  1110. }
  1111. return "FALSE", nil
  1112. case 20, 21, 23, 26, 700, 701, 1700:
  1113. if _, err := strconv.ParseFloat(value, 64); err != nil {
  1114. return "", fmt.Errorf("invalid numeric value")
  1115. }
  1116. return value, nil
  1117. default:
  1118. return "'" + strings.ReplaceAll(value, "'", "''") + "'", nil
  1119. }
  1120. }
  1121. // sendResult sends a statement's result. columnTypes are the types reported in
  1122. // RowDescription (already corrected for BLOB values) and formats are the
  1123. // portal's resolved per-column format codes, or nil for all-text results.
  1124. func (c *Connection) sendResult(result *executor.Result, stmt parser.Statement, columnTypes []string, formats []int16) error {
  1125. // Any statement that produced a row set (SELECT, or INSERT/UPDATE/DELETE
  1126. // with RETURNING) sends a row description and its data rows. Other
  1127. // statements only send the command completion tag.
  1128. if len(result.Columns) > 0 {
  1129. oids := c.resultColumnOIDs(columnTypes, len(result.Columns))
  1130. if err := c.sendRowDescriptionFormats(result.Columns, columnTypes, oids, formats); err != nil {
  1131. return err
  1132. }
  1133. for _, row := range result.Rows {
  1134. if err := c.sendDataRowFormats(row, oids, formats); err != nil {
  1135. return c.failBinaryEncode(err)
  1136. }
  1137. }
  1138. return c.sendCommandComplete(c.getCommandTag(stmt, result))
  1139. }
  1140. // For other statements, just send command complete
  1141. tag := c.getCommandTag(stmt, result)
  1142. return c.sendCommandComplete(tag)
  1143. }
  1144. // wireColumnTypes corrects declared-affinity metadata when SQLite has stored a
  1145. // value of another type. In particular, binding []byte to a VARCHAR column is
  1146. // still a BLOB in SQLite; advertising TEXT while encoding PostgreSQL bytea text
  1147. // would make clients receive the literal "\\x..." instead of the original
  1148. // bytes.
  1149. func wireColumnTypes(result *executor.Result) []string {
  1150. types := append([]string(nil), result.ColumnTypes...)
  1151. if len(types) < len(result.Columns) {
  1152. types = append(types, make([]string, len(result.Columns)-len(types))...)
  1153. }
  1154. for _, row := range result.Rows {
  1155. for i, value := range row {
  1156. if i >= len(types) {
  1157. break
  1158. }
  1159. if _, ok := value.([]byte); ok {
  1160. types[i] = "BLOB"
  1161. }
  1162. }
  1163. }
  1164. return types
  1165. }
  1166. // getCommandTag returns the command completion tag
  1167. func (c *Connection) getCommandTag(stmt parser.Statement, result *executor.Result) string {
  1168. switch s := stmt.(type) {
  1169. case *parser.SelectStmt:
  1170. return fmt.Sprintf("SELECT %d", len(result.Rows))
  1171. case *parser.CreateTableStmt:
  1172. return "CREATE TABLE"
  1173. case *parser.DropTableStmt:
  1174. return "DROP TABLE"
  1175. case *parser.CreateIndexStmt:
  1176. return "CREATE INDEX"
  1177. case *parser.DropIndexStmt:
  1178. return "DROP INDEX"
  1179. case *parser.AlterTableStmt:
  1180. return "ALTER TABLE"
  1181. case *parser.InsertStmt:
  1182. return fmt.Sprintf("INSERT 0 %d", result.RowsAffected)
  1183. case *parser.UpdateStmt:
  1184. return fmt.Sprintf("UPDATE %d", result.RowsAffected)
  1185. case *parser.DeleteStmt:
  1186. return fmt.Sprintf("DELETE %d", result.RowsAffected)
  1187. case *parser.BeginStmt:
  1188. c.txStatus = TxStatusInBlock
  1189. return "BEGIN"
  1190. case *parser.CommitStmt:
  1191. c.txStatus = TxStatusIdle
  1192. return "COMMIT"
  1193. case *parser.RollbackStmt:
  1194. if s.Savepoint != "" {
  1195. c.txStatus = TxStatusInBlock
  1196. return "ROLLBACK"
  1197. }
  1198. c.txStatus = TxStatusIdle
  1199. return "ROLLBACK"
  1200. case *parser.SavepointStmt:
  1201. c.txStatus = TxStatusInBlock
  1202. return "SAVEPOINT"
  1203. case *parser.ReleaseStmt:
  1204. c.txStatus = TxStatusInBlock
  1205. return "RELEASE"
  1206. case *parser.ListenStmt:
  1207. return "LISTEN"
  1208. case *parser.UnlistenStmt:
  1209. return "UNLISTEN"
  1210. case *parser.NotifyStmt:
  1211. return "NOTIFY"
  1212. default:
  1213. return "OK"
  1214. }
  1215. }
  1216. // sendAuthenticationOk sends authentication OK message
  1217. func (c *Connection) sendAuthenticationOk() error {
  1218. mb := NewMessageBuilder()
  1219. mb.WriteInt32(0) // Auth OK
  1220. return c.writeMessage(MsgAuthenticationOk, mb.Bytes())
  1221. }
  1222. // drainNotifications writes every notification currently buffered for this
  1223. // session. It is called at protocol-safe points (after Sync/ReadyForQuery).
  1224. func (c *Connection) drainNotifications() error {
  1225. ch := c.executor.NotificationChannel()
  1226. for {
  1227. select {
  1228. case n := <-ch:
  1229. if err := c.sendNotification(n); err != nil {
  1230. return err
  1231. }
  1232. default:
  1233. return c.writer.Flush()
  1234. }
  1235. }
  1236. }
  1237. // sendNotification writes a NotificationResponse frame. The frame is only
  1238. // written by the connection's main goroutine, never from a publisher.
  1239. func (c *Connection) sendNotification(n storage.Notification) error {
  1240. mb := NewMessageBuilder()
  1241. mb.WriteInt32(n.PID)
  1242. mb.WriteString(n.Channel)
  1243. mb.WriteString(n.Payload)
  1244. return c.writeMessage(MsgNotificationResponse, mb.Bytes())
  1245. }
  1246. // sendLSN exposes the last commit LSN as a ParameterStatus. Drivers that do
  1247. // not know the key ignore it; subscribers can use it as an ordering cursor.
  1248. func (c *Connection) sendLSN(lsn uint64) error {
  1249. return c.sendParameterStatus("pizzasql.lsn", strconv.FormatUint(lsn, 10))
  1250. }
  1251. // sendParameterStatus sends a parameter status message
  1252. func (c *Connection) sendParameterStatus(name, value string) error {
  1253. mb := NewMessageBuilder()
  1254. mb.WriteString(name)
  1255. mb.WriteString(value)
  1256. return c.writeMessage(MsgParameterStatus, mb.Bytes())
  1257. }
  1258. // sendBackendKeyData sends backend key data
  1259. func (c *Connection) sendBackendKeyData(processID, secretKey int32) error {
  1260. mb := NewMessageBuilder()
  1261. mb.WriteInt32(processID)
  1262. mb.WriteInt32(secretKey)
  1263. return c.writeMessage(MsgBackendKeyData, mb.Bytes())
  1264. }
  1265. // isIdleRollback reports whether a bare ROLLBACK found no transaction to roll
  1266. // back. A COMMIT rejected by storage has already ended the transaction, so the
  1267. // client's cleanup ROLLBACK must complete (PostgreSQL reports a warning and
  1268. // succeeds) instead of surfacing an internal error on an idle session.
  1269. func isIdleRollback(stmt parser.Statement, status byte, err error) bool {
  1270. rollback, ok := stmt.(*parser.RollbackStmt)
  1271. if !ok || rollback.Savepoint != "" {
  1272. return false
  1273. }
  1274. return status == TxStatusIdle && errors.Is(err, executor.ErrNoTransaction)
  1275. }
  1276. // sendReadyForQuery sends ready for query message
  1277. func (c *Connection) sendReadyForQuery() error {
  1278. if c.txStatus == TxStatusIdle {
  1279. // The transaction this cycle ran in ends here, so its portals do too.
  1280. // A portal inside an explicit block survives (status T) until
  1281. // COMMIT/ROLLBACK, and a failed block (status E) keeps its portals so
  1282. // Execute still reports 25P02 until the transaction is rolled back.
  1283. c.clearPortals()
  1284. }
  1285. mb := NewMessageBuilder()
  1286. mb.AppendByte(c.txStatus)
  1287. if err := c.writeMessage(MsgReadyForQuery, mb.Bytes()); err != nil {
  1288. return err
  1289. }
  1290. // ReadyForQuery closes out a response cycle, so flush everything buffered
  1291. // so far. This is what makes simple-query results and Sync responses
  1292. // visible to the client.
  1293. return c.writer.Flush()
  1294. }
  1295. // sendEmptyQueryResponse sends empty query response
  1296. func (c *Connection) sendEmptyQueryResponse() error {
  1297. return c.writeMessage(MsgEmptyQueryResponse, []byte{})
  1298. }
  1299. // sendParameterDescription reports the negotiated parameter types of a
  1300. // prepared statement. The protocol count field is 16-bit and the negotiated
  1301. // list never exceeds maxParameterNumber, so the conversion cannot lose a count.
  1302. func (c *Connection) sendParameterDescription(oids []int32) error {
  1303. if len(oids) > maxParameterNumber {
  1304. return fmt.Errorf("parameter description has %d entries; the protocol limit is %d", len(oids), maxParameterNumber)
  1305. }
  1306. mb := NewMessageBuilder()
  1307. mb.WriteInt16(int16(uint16(len(oids))))
  1308. for _, oid := range oids {
  1309. mb.WriteInt32(oid)
  1310. }
  1311. return c.writeMessage(MsgParameterDescription, mb.Bytes())
  1312. }
  1313. // sendRowDescription sends row description (column metadata) in text format.
  1314. func (c *Connection) sendRowDescription(columns []string, columnTypes []string) error {
  1315. return c.sendRowDescriptionFormats(columns, columnTypes, c.resultColumnOIDs(columnTypes, len(columns)), nil)
  1316. }
  1317. // sendRowDescriptionFormats sends row description with the per-column formats a
  1318. // portal resolved at Bind. PostgreSQL reports the bound formats in a portal
  1319. // RowDescription; this server emits its RowDescription at Execute instead of
  1320. // Describe, so the portal's formats travel with the row metadata. OIDs are the
  1321. // same for text and binary results.
  1322. func (c *Connection) sendRowDescriptionFormats(columns []string, columnTypes []string, oids []int32, formats []int16) error {
  1323. mb := NewMessageBuilder()
  1324. mb.WriteInt16(int16(len(columns)))
  1325. for i, col := range columns {
  1326. colType := typeNameAt(columnTypes, i)
  1327. format := int16(0)
  1328. if i < len(formats) {
  1329. format = formats[i]
  1330. }
  1331. mb.WriteString(col)
  1332. mb.WriteInt32(0) // table OID
  1333. mb.WriteInt16(0) // column attribute number
  1334. mb.WriteInt32(oids[i]) // type OID
  1335. mb.WriteInt16(c.getTypeSizeForType(colType)) // type size
  1336. mb.WriteInt32(-1) // type modifier
  1337. mb.WriteInt16(format) // format code
  1338. }
  1339. return c.writeMessage(MsgRowDescription, mb.Bytes())
  1340. }
  1341. // resultColumnOIDs returns the PostgreSQL OID reported for every result column.
  1342. func (c *Connection) resultColumnOIDs(columnTypes []string, columnCount int) []int32 {
  1343. oids := make([]int32, columnCount)
  1344. for i := range oids {
  1345. oids[i] = c.getOIDForType(typeNameAt(columnTypes, i))
  1346. }
  1347. return oids
  1348. }
  1349. // sendDataRow sends a data row in text format
  1350. func (c *Connection) sendDataRow(row []interface{}, columns []string) error {
  1351. return c.sendDataRowFormats(row, nil, nil)
  1352. }
  1353. // sendDataRowFormats sends one DataRow, choosing text or binary encoding per
  1354. // column from formats. NULL is always length -1. Binary values are appended
  1355. // directly into the DataRow buffer; a value that cannot be encoded fails before
  1356. // the row is written, so the client never receives a partial DataRow.
  1357. func (c *Connection) sendDataRowFormats(row []interface{}, oids []int32, formats []int16) error {
  1358. mb := NewMessageBuilder()
  1359. mb.WriteInt16(int16(len(row)))
  1360. for i, value := range row {
  1361. if value == nil {
  1362. mb.WriteInt32(-1) // NULL indicator
  1363. continue
  1364. }
  1365. format := int16(0)
  1366. if i < len(formats) {
  1367. format = formats[i]
  1368. }
  1369. if format == 0 {
  1370. strValue := c.valueToString(value)
  1371. mb.WriteInt32(int32(len(strValue)))
  1372. mb.WriteBytes([]byte(strValue))
  1373. continue
  1374. }
  1375. oid := int32(25) // TEXT, the fallback RowDescription OID
  1376. if i < len(oids) {
  1377. oid = oids[i]
  1378. }
  1379. err := mb.AppendBinary(func(dst []byte) ([]byte, error) {
  1380. return appendBinaryResultValue(dst, oid, value)
  1381. })
  1382. if err != nil {
  1383. return fmt.Errorf("binary result column %d: %w", i+1, err)
  1384. }
  1385. }
  1386. return c.writeMessage(MsgDataRow, mb.Bytes())
  1387. }
  1388. // sendCommandComplete sends command complete message
  1389. func (c *Connection) sendCommandComplete(tag string) error {
  1390. mb := NewMessageBuilder()
  1391. mb.WriteString(tag)
  1392. return c.writeMessage(MsgCommandComplete, mb.Bytes())
  1393. }
  1394. // sendPortalSuspended reports that a bounded Execute stopped at its row limit
  1395. // with rows left to fetch.
  1396. func (c *Connection) sendPortalSuspended() error {
  1397. return c.writeMessage(MsgPortalSuspended, nil)
  1398. }
  1399. // sendError sends an error response
  1400. func (c *Connection) sendError(severity, code, message string) error {
  1401. if severity == "ERROR" && c.txStatus == TxStatusInBlock {
  1402. c.txStatus = TxStatusFailed
  1403. }
  1404. mb := NewMessageBuilder()
  1405. mb.AppendByte(ErrorFieldSeverity)
  1406. mb.WriteString(severity)
  1407. mb.AppendByte(ErrorFieldCode)
  1408. mb.WriteString(code)
  1409. mb.AppendByte(ErrorFieldMessage)
  1410. mb.WriteString(message)
  1411. mb.AppendByte(0) // Terminator
  1412. if err := c.writeMessage(MsgErrorResponse, mb.Bytes()); err != nil {
  1413. return err
  1414. }
  1415. // Errors must be visible promptly, including FATAL startup failures that
  1416. // are not followed by a ReadyForQuery before the connection closes.
  1417. return c.writer.Flush()
  1418. }
  1419. // writeMessage buffers a message for the connection. It does not flush, so
  1420. // callers that need to make a response visible to the client must flush at the
  1421. // appropriate protocol boundary (ReadyForQuery, an explicit Flush message, or
  1422. // an error response). Buffering amortizes the per-message syscalls that a
  1423. // result set would otherwise incur; the underlying bufio.Writer bounds memory
  1424. // use so large result sets cannot grow the buffer without limit.
  1425. func (c *Connection) writeMessage(msgType byte, data []byte) error {
  1426. if !c.quiet {
  1427. log.Printf("Sending message type=%c length=%d", msgType, len(data)+4)
  1428. }
  1429. return WriteMessage(c.writer, msgType, data)
  1430. }
  1431. // arrayElementTypeName reports the element type of an array type name such as
  1432. // "INTEGER[]". It reports false for scalar type names.
  1433. func arrayElementTypeName(typeName string) (string, bool) {
  1434. upper := strings.ToUpper(strings.TrimSpace(typeName))
  1435. if !strings.HasSuffix(upper, "[]") {
  1436. return "", false
  1437. }
  1438. return strings.TrimSpace(strings.TrimSuffix(upper, "[]")), true
  1439. }
  1440. // arrayOIDForElement maps an array element type name to its PostgreSQL array
  1441. // OID. Narrower integer types report int8[] because values are not
  1442. // range-checked, matching the scalar carrier rule; NUMERIC reports numeric[]
  1443. // because array elements stay text.
  1444. func arrayOIDForElement(element string) int32 {
  1445. base := strings.ToUpper(strings.TrimSpace(element))
  1446. if idx := strings.IndexByte(base, '('); idx >= 0 {
  1447. base = strings.TrimSpace(base[:idx])
  1448. }
  1449. switch base {
  1450. case "INTEGER", "INT", "INT4":
  1451. return 1007 // INT4ARRAYOID
  1452. case "BIGINT", "INT8", "SMALLINT", "INT2", "TINYINT", "MEDIUMINT":
  1453. return 1016 // INT8ARRAYOID
  1454. case "BOOLEAN", "BOOL":
  1455. return 1000 // BOOLARRAYOID
  1456. case "REAL", "FLOAT", "FLOAT4":
  1457. return 1021 // FLOAT4ARRAYOID
  1458. case "DOUBLE", "DOUBLE PRECISION", "FLOAT8":
  1459. return 1022 // FLOAT8ARRAYOID
  1460. case "NUMERIC", "DECIMAL":
  1461. return 1231 // NUMERICARRAYOID
  1462. case "VARCHAR", "NVARCHAR", "CHARACTER VARYING":
  1463. return 1015 // VARCHARARRAYOID
  1464. default:
  1465. return 1009 // TEXTARRAYOID
  1466. }
  1467. }
  1468. // arrayParamElementType maps an array parameter OID to the element type the
  1469. // bound literal is cast to. Unknown OIDs are handled by callers.
  1470. func arrayParamElementType(oid int32) (string, bool) {
  1471. switch oid {
  1472. case 1009:
  1473. return "TEXT", true
  1474. case 1015:
  1475. return "VARCHAR", true
  1476. case 1007:
  1477. return "INTEGER", true
  1478. case 1016:
  1479. return "BIGINT", true
  1480. case 1005:
  1481. return "SMALLINT", true
  1482. case 1000:
  1483. return "BOOLEAN", true
  1484. case 1021:
  1485. return "REAL", true
  1486. case 1022:
  1487. return "DOUBLE", true
  1488. case 1231:
  1489. return "NUMERIC", true
  1490. default:
  1491. return "", false
  1492. }
  1493. }
  1494. // getOIDForType returns PostgreSQL OID for type.
  1495. //
  1496. // Types narrower than the value the engine carries are reported as the carrier
  1497. // type, because the engine does not range-check stored or cast values: a value
  1498. // that does not fit int2/int4 or float4 would fail client-side decoding rather
  1499. // than having been rejected on write. INTEGER and REAL keep their declared
  1500. // mappings, which predate this rule and are what existing clients expect.
  1501. func (c *Connection) getOIDForType(typeName string) int32 {
  1502. if element, ok := arrayElementTypeName(typeName); ok {
  1503. return arrayOIDForElement(element)
  1504. }
  1505. switch strings.ToUpper(typeName) {
  1506. case "SMALLINT", "INT2", "TINYINT", "MEDIUMINT":
  1507. // Carried as int64 and not range-checked, so int8 is the honest type.
  1508. return 20 // INT8OID
  1509. case "INTEGER", "INT", "INT4":
  1510. return 23 // INT4OID
  1511. case "BIGINT", "INT8":
  1512. return 20 // INT8OID
  1513. case "NUMERIC", "DECIMAL":
  1514. // Values round-trip through JSON as float64; there is no exact decimal
  1515. // carrier, so NUMERIC is not advertised.
  1516. return 701 // FLOAT8OID
  1517. case "JSONB":
  1518. return 3802 // JSONBOID
  1519. case "OID":
  1520. return 26 // OIDOID
  1521. case "REGCLASS":
  1522. return 2205 // REGCLASSOID
  1523. case "REGTYPE":
  1524. return 2206 // REGTYPEOID
  1525. case "REGPROC":
  1526. // pg_type.typinput and friends are regproc attributes.
  1527. return 24 // REGPROCOID
  1528. case "NAME":
  1529. return 19 // NAMEOID
  1530. case "TEXT", "VARCHAR", "CHAR", "UUID":
  1531. // UUID is stored as text (SQLite-style), so it reports TEXTOID rather
  1532. // than the native PG UUID OID.
  1533. return 25 // TEXTOID
  1534. case "REAL", "FLOAT", "FLOAT4":
  1535. return 700 // FLOAT4OID
  1536. case "DOUBLE", "FLOAT8":
  1537. return 701 // FLOAT8OID
  1538. case "BOOLEAN", "BOOL":
  1539. return 16 // BOOLOID
  1540. case "BLOB":
  1541. return 17 // BYTEAOID
  1542. case "DATETIME", "TIMESTAMP":
  1543. // Datetime values are exchanged as UTC RFC3339 (ISO8601 with a timezone
  1544. // offset), which timestamptz decodes directly.
  1545. return 1184 // TIMESTAMPTZOID
  1546. case "DATE":
  1547. return 1082 // DATEOID
  1548. default:
  1549. return 25 // Default to TEXT
  1550. }
  1551. }
  1552. // getTypeSizeForType returns type size in bytes, or -1 for variable length.
  1553. func (c *Connection) getTypeSizeForType(typeName string) int16 {
  1554. if _, ok := arrayElementTypeName(typeName); ok {
  1555. return -1 // arrays are variable length
  1556. }
  1557. switch strings.ToUpper(typeName) {
  1558. case "SMALLINT", "INT2", "TINYINT", "MEDIUMINT":
  1559. return 8 // Reported as int8; see getOIDForType.
  1560. case "INTEGER", "INT", "INT4":
  1561. return 4
  1562. case "BIGINT", "INT8":
  1563. return 8
  1564. case "NUMERIC", "DECIMAL":
  1565. return 8 // Reported as float8; see getOIDForType.
  1566. case "REAL", "FLOAT", "FLOAT4":
  1567. return 4
  1568. case "DOUBLE", "FLOAT8":
  1569. return 8
  1570. case "BOOLEAN", "BOOL":
  1571. return 1
  1572. case "DATETIME", "TIMESTAMP":
  1573. return 8
  1574. case "DATE":
  1575. return 4
  1576. case "OID", "REGCLASS", "REGTYPE", "REGPROC":
  1577. return 4
  1578. case "NAME":
  1579. return 64
  1580. default:
  1581. return -1 // Variable length
  1582. }
  1583. }
  1584. // valueToString converts a value to its PostgreSQL text representation
  1585. func (c *Connection) valueToString(value interface{}) string {
  1586. return textValueString(value)
  1587. }
  1588. // textValueString is the text representation the wire layer sends for a value.
  1589. // Binary text and bytea results reuse it so both formats carry the same bytes
  1590. // for values without a native binary form. PostgreSQL's text format for bytea is
  1591. // \x followed by hex, which lets libpq/pgx decode a BLOB column (OID 17)
  1592. // losslessly.
  1593. func textValueString(value interface{}) string {
  1594. if value == nil {
  1595. return ""
  1596. }
  1597. if b, ok := value.([]byte); ok {
  1598. return `\x` + hex.EncodeToString(b)
  1599. }
  1600. return fmt.Sprintf("%v", value)
  1601. }
  1602. // handleVersionQuery handles SELECT version()
  1603. func (c *Connection) handleVersionQuery() error {
  1604. columns := []string{"version"}
  1605. columnTypes := []string{"TEXT"}
  1606. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1607. return err
  1608. }
  1609. row := []interface{}{"PostgreSQL " + version.PostgreSQLCompatVersion + " (PizzaSQL)"}
  1610. if err := c.sendDataRow(row, columns); err != nil {
  1611. return err
  1612. }
  1613. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1614. return err
  1615. }
  1616. return c.sendReadyForQuery()
  1617. }
  1618. // handleCurrentUserQuery handles SELECT current_user
  1619. func (c *Connection) handleCurrentUserQuery() error {
  1620. columns := []string{"current_user"}
  1621. columnTypes := []string{"TEXT"}
  1622. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1623. return err
  1624. }
  1625. user := c.params["user"]
  1626. if user == "" {
  1627. user = "pizzasql"
  1628. }
  1629. row := []interface{}{user}
  1630. if err := c.sendDataRow(row, columns); err != nil {
  1631. return err
  1632. }
  1633. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1634. return err
  1635. }
  1636. return c.sendReadyForQuery()
  1637. }
  1638. // handleShowCommand handles SHOW commands
  1639. func (c *Connection) handleShowCommand(sqlUpper string) error {
  1640. var value string
  1641. var name string
  1642. if sqlUpper == "SERVER_VERSION" {
  1643. name = "server_version"
  1644. value = version.PostgreSQLCompatVersion
  1645. } else if sqlUpper == "SERVER_ENCODING" {
  1646. name = "server_encoding"
  1647. value = "UTF8"
  1648. } else if sqlUpper == "CLIENT_ENCODING" {
  1649. name = "client_encoding"
  1650. value = "UTF8"
  1651. } else {
  1652. // Unknown SHOW command
  1653. c.sendError("ERROR", ErrCodeFeatureNotSupported, "SHOW command not supported")
  1654. return c.sendReadyForQuery()
  1655. }
  1656. columns := []string{name}
  1657. columnTypes := []string{"TEXT"}
  1658. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1659. return err
  1660. }
  1661. row := []interface{}{value}
  1662. if err := c.sendDataRow(row, columns); err != nil {
  1663. return err
  1664. }
  1665. if err := c.sendCommandComplete("SHOW"); err != nil {
  1666. return err
  1667. }
  1668. return c.sendReadyForQuery()
  1669. }
  1670. // isRollbackStatement reports whether sql parses as a single ROLLBACK
  1671. // statement, including ROLLBACK TO SAVEPOINT.
  1672. func isRollbackStatement(sql string) bool {
  1673. stmt, err := parser.New(lexer.New(sql)).Parse()
  1674. if err != nil {
  1675. return false
  1676. }
  1677. _, ok := stmt.(*parser.RollbackStmt)
  1678. return ok
  1679. }