connection.go 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840
  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.ErrLockNotAvailable) {
  413. code = ErrCodeLockNotAvailable
  414. if c.txStatus == TxStatusInBlock {
  415. c.txStatus = TxStatusFailed
  416. }
  417. } else if errors.Is(err, pgerror.ErrDeadlockDetected) {
  418. code = ErrCodeDeadlockDetected
  419. if c.txStatus == TxStatusInBlock {
  420. c.txStatus = TxStatusFailed
  421. }
  422. } else if errors.Is(err, pgerror.ErrInvalidText) {
  423. code = ErrCodeInvalidText
  424. if c.txStatus == TxStatusInBlock {
  425. c.txStatus = TxStatusFailed
  426. }
  427. } else if errors.Is(err, pgerror.ErrInvalidParameter) {
  428. code = ErrCodeInvalidParameter
  429. if c.txStatus == TxStatusInBlock {
  430. c.txStatus = TxStatusFailed
  431. }
  432. } else if errors.Is(err, pgerror.ErrDatatypeMismatch) {
  433. code = ErrCodeDatatypeMismatch
  434. if c.txStatus == TxStatusInBlock {
  435. c.txStatus = TxStatusFailed
  436. }
  437. } else if errors.Is(err, pgerror.ErrInvalidColumnReference) {
  438. code = ErrCodeInvalidColumnReference
  439. if c.txStatus == TxStatusInBlock {
  440. c.txStatus = TxStatusFailed
  441. }
  442. } else if errors.Is(err, pgerror.ErrUndefinedTable) || analysisUndefinedTable(err) {
  443. code = ErrCodeUndefinedTable
  444. if c.txStatus == TxStatusInBlock {
  445. c.txStatus = TxStatusFailed
  446. }
  447. } else if analysisErr := analysisTypeMismatch(err); analysisErr {
  448. code = ErrCodeDatatypeMismatch
  449. if c.txStatus == TxStatusInBlock {
  450. c.txStatus = TxStatusFailed
  451. }
  452. } else if errors.As(err, &notNullErr) {
  453. code = "23502"
  454. if _, commit := stmt.(*parser.CommitStmt); commit {
  455. c.txStatus = TxStatusIdle
  456. } else if c.txStatus == TxStatusInBlock {
  457. c.txStatus = TxStatusFailed
  458. }
  459. } else if errors.As(err, &checkErr) {
  460. code = ErrCodeCheckViolation
  461. if _, commit := stmt.(*parser.CommitStmt); commit {
  462. c.txStatus = TxStatusIdle
  463. } else if c.txStatus == TxStatusInBlock {
  464. c.txStatus = TxStatusFailed
  465. }
  466. } else if errors.As(err, &foreignKeyErr) {
  467. code = ErrCodeForeignKeyViolation
  468. if _, commit := stmt.(*parser.CommitStmt); commit {
  469. c.txStatus = TxStatusIdle
  470. } else if c.txStatus == TxStatusInBlock {
  471. c.txStatus = TxStatusFailed
  472. }
  473. } else if errors.As(err, &uniqueErr) || errors.As(err, &primaryKeyErr) {
  474. code = ErrCodeUniqueViolation
  475. if uniqueErr != nil {
  476. message = fmt.Sprintf("Execution error: UNIQUE constraint failed: %s", uniqueErr.Constraint)
  477. }
  478. if _, commit := stmt.(*parser.CommitStmt); commit {
  479. c.txStatus = TxStatusIdle
  480. } else if c.txStatus == TxStatusInBlock {
  481. c.txStatus = TxStatusFailed
  482. }
  483. } else if errors.Is(err, pgerror.ErrFeatureNotSupported) || errors.Is(err, executor.ErrUnsupportedFeature) {
  484. code = ErrCodeFeatureNotSupported
  485. if c.txStatus == TxStatusInBlock {
  486. c.txStatus = TxStatusFailed
  487. }
  488. } else if _, commit := stmt.(*parser.CommitStmt); commit {
  489. // A failed COMMIT has already rolled the transaction back in
  490. // storage; leaving the session in the failed state would make
  491. // every following statement (including ROLLBACK) fail.
  492. c.txStatus = TxStatusIdle
  493. } else if c.txStatus == TxStatusInBlock {
  494. c.txStatus = TxStatusFailed
  495. }
  496. c.sendError("ERROR", code, message)
  497. return c.sendReadyForQuery()
  498. }
  499. if err := c.sendResult(result, stmt, wireColumnTypes(result), nil); err != nil {
  500. return err
  501. }
  502. if result.LSN > 0 {
  503. if err := c.sendLSN(result.LSN); err != nil {
  504. return err
  505. }
  506. }
  507. if resetsPortals(stmt) {
  508. // Same rule as the extended path: a transaction end or a savepoint
  509. // rollback invalidates every open portal. sendReadyForQuery covers
  510. // the idle case; ROLLBACK TO SAVEPOINT keeps the block open and
  511. // needs this explicit clear.
  512. c.clearPortals()
  513. }
  514. }
  515. return c.sendReadyForQuery()
  516. }
  517. func (c *Connection) handleParse(msg *Message) error {
  518. if c.extendedFailed {
  519. return nil
  520. }
  521. name, pos, err := readCString(msg.Data, 0)
  522. if err != nil {
  523. return c.failExtended(ErrCodeProtocolViolation, err)
  524. }
  525. query, pos, err := readCString(msg.Data, pos)
  526. if err != nil || pos+2 > len(msg.Data) {
  527. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Parse message"))
  528. }
  529. count := int(binary.BigEndian.Uint16(msg.Data[pos : pos+2]))
  530. pos += 2
  531. if pos+count*4 != len(msg.Data) {
  532. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Parse parameter list"))
  533. }
  534. oids := make([]int32, count)
  535. for i := range oids {
  536. oids[i] = int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  537. pos += 4
  538. }
  539. if !isSingleStatementSQL(query) {
  540. return c.failExtended(ErrCodeSyntaxError, fmt.Errorf("prepared statements must contain one command"))
  541. }
  542. paramOIDs, err := c.negotiateParameterOIDs(query, oids)
  543. if err != nil {
  544. return c.failExtended(ErrCodeProgramLimitExceeded, err)
  545. }
  546. c.statements[name] = &preparedStatement{query: query, paramOIDs: paramOIDs}
  547. return c.writeMessage(MsgParseComplete, nil)
  548. }
  549. func (c *Connection) handleBind(msg *Message) error {
  550. if c.extendedFailed {
  551. return nil
  552. }
  553. portalName, pos, err := readCString(msg.Data, 0)
  554. if err != nil {
  555. return c.failExtended(ErrCodeProtocolViolation, err)
  556. }
  557. statementName, pos, err := readCString(msg.Data, pos)
  558. if err != nil {
  559. return c.failExtended(ErrCodeProtocolViolation, err)
  560. }
  561. statement, ok := c.statements[statementName]
  562. if !ok {
  563. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("prepared statement %q does not exist", statementName))
  564. }
  565. // Named portals cannot be replaced: PostgreSQL reports 42P03 and leaves the
  566. // existing portal in place. Only the unnamed portal is re-bound freely,
  567. // because the new Bind replaces it.
  568. if portalName != "" {
  569. if _, exists := c.portals[portalName]; exists {
  570. return c.failExtended(ErrCodeDuplicateCursor, fmt.Errorf("portal %q already exists", portalName))
  571. }
  572. }
  573. formats, pos, err := readInt16List(msg.Data, pos)
  574. if err != nil || pos+2 > len(msg.Data) {
  575. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind format list"))
  576. }
  577. paramCount := int(binary.BigEndian.Uint16(msg.Data[pos : pos+2]))
  578. pos += 2
  579. if len(formats) > 1 && len(formats) != paramCount {
  580. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("Bind parameter format count does not match parameters"))
  581. }
  582. for _, format := range formats {
  583. if format != 0 && format != 1 {
  584. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter format code"))
  585. }
  586. }
  587. params := make([]boundParameter, paramCount)
  588. for i := range params {
  589. if pos+4 > len(msg.Data) {
  590. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter"))
  591. }
  592. length := int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  593. pos += 4
  594. params[i].oid = parameterOID(statement.paramOIDs, i)
  595. params[i].format = parameterFormat(formats, i)
  596. if length == -1 {
  597. params[i].null = true
  598. continue
  599. }
  600. if length < 0 || pos+int(length) > len(msg.Data) {
  601. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter length"))
  602. }
  603. params[i].value = append([]byte(nil), msg.Data[pos:pos+int(length)]...)
  604. pos += int(length)
  605. }
  606. resultFormats, pos, err := readInt16List(msg.Data, pos)
  607. if err != nil || pos != len(msg.Data) {
  608. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind result format list"))
  609. }
  610. for _, format := range resultFormats {
  611. if format != 0 && format != 1 {
  612. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind result format code"))
  613. }
  614. }
  615. query, err := bindQuery(statement.query, params)
  616. if err != nil {
  617. code := ErrCodeInvalidParameter
  618. if errors.Is(err, pgerror.ErrFeatureNotSupported) {
  619. code = ErrCodeFeatureNotSupported
  620. }
  621. if errors.Is(err, pgerror.ErrInvalidText) {
  622. code = ErrCodeInvalidText
  623. }
  624. if errors.Is(err, pgerror.ErrInvalidParameter) {
  625. code = ErrCodeInvalidParameter
  626. }
  627. return c.failExtended(code, err)
  628. }
  629. c.portals[portalName] = &portal{query: query, resultFormats: resultFormats}
  630. return c.writeMessage(MsgBindComplete, nil)
  631. }
  632. func (c *Connection) handleDescribe(msg *Message) error {
  633. if c.extendedFailed {
  634. return nil
  635. }
  636. if len(msg.Data) < 2 {
  637. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe message"))
  638. }
  639. name, pos, err := readCString(msg.Data, 1)
  640. if err != nil || pos != len(msg.Data) {
  641. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe name"))
  642. }
  643. switch msg.Data[0] {
  644. case 'S':
  645. statement, ok := c.statements[name]
  646. if !ok {
  647. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("prepared statement %q does not exist", name))
  648. }
  649. if err := c.sendParameterDescription(statement.paramOIDs); err != nil {
  650. return err
  651. }
  652. case 'P':
  653. // PostgreSQL reports parameter types only for Describe('S'). Portal
  654. // Describe returns row metadata (here NoData) without a
  655. // ParameterDescription.
  656. if _, ok := c.portals[name]; !ok {
  657. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("portal %q does not exist", name))
  658. }
  659. default:
  660. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe target"))
  661. }
  662. // Row metadata requires analysis without side effects. Return NoData for
  663. // compatibility; Execute still emits the real RowDescription. This is the
  664. // pre-0.4.0 behavior used by common extended-protocol clients.
  665. return c.writeMessage(MsgNoData, nil)
  666. }
  667. func (c *Connection) handleExecute(msg *Message) error {
  668. if c.extendedFailed {
  669. return nil
  670. }
  671. name, pos, err := readCString(msg.Data, 0)
  672. if err != nil || pos+4 != len(msg.Data) {
  673. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Execute message"))
  674. }
  675. portal, ok := c.portals[name]
  676. if !ok {
  677. return c.failExtended(ErrCodeUndefinedCursor, fmt.Errorf("portal %q does not exist", name))
  678. }
  679. maxRows := int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  680. if maxRows < 0 {
  681. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Execute row limit: %d", maxRows))
  682. }
  683. // Check the transaction state before catalog emulation. Catalog queries do
  684. // not all parse as regular PizzaSQL statements, but must still return 25P02
  685. // while the transaction is aborted.
  686. if c.txStatus == TxStatusFailed && !isRollbackStatement(portal.query) {
  687. return c.failExtended(ErrCodeTransactionAborted, fmt.Errorf("current transaction is aborted, commands ignored until end of transaction block"))
  688. }
  689. if portal.execution == nil {
  690. if failure := c.materializePortal(portal); failure != nil {
  691. return c.failExtended(failure.code, failure.err)
  692. }
  693. }
  694. if err := c.sendPortalRows(portal, maxRows); err != nil {
  695. return err
  696. }
  697. if portal.execution.clearsPortals {
  698. c.clearPortals()
  699. }
  700. return nil
  701. }
  702. // executeError is a rejected Execute. Its transaction-state effects have already
  703. // been applied by the time it is built, so handleExecute only reports it.
  704. type executeError struct {
  705. code string
  706. err error
  707. }
  708. // materializePortal runs a portal's statement once and stores everything the
  709. // Execute responses need. The executor already produces a complete result, so a
  710. // resumed Execute stays a slice of that result and never runs the SQL again;
  711. // column metadata and the completion tag are also computed once. A nil return
  712. // means the portal is ready to stream.
  713. func (c *Connection) materializePortal(portal *portal) *executeError {
  714. execution := &portalExecution{}
  715. stmt, err := parser.New(lexer.New(portal.query)).Parse()
  716. if err != nil {
  717. code := ErrCodeSyntaxError
  718. if errors.Is(err, pgerror.ErrFeatureNotSupported) {
  719. code = ErrCodeFeatureNotSupported
  720. if c.txStatus == TxStatusInBlock {
  721. c.txStatus = TxStatusFailed
  722. }
  723. }
  724. return &executeError{code: code, err: fmt.Errorf("syntax error: %w", err)}
  725. }
  726. result, err := c.executor.Execute(stmt)
  727. if err != nil && isIdleRollback(stmt, c.txStatus, err) {
  728. result, err = executor.NewResult("ROLLBACK"), nil
  729. }
  730. if err != nil {
  731. return c.classifyExecuteError(stmt, err)
  732. }
  733. execution.result = result
  734. // getCommandTag applies the statement's transaction transition, so it
  735. // belongs here: a repeated Execute must not replay BEGIN/COMMIT/ROLLBACK.
  736. execution.commandTag = c.getCommandTag(stmt, result)
  737. execution.clearsPortals = resetsPortals(stmt)
  738. columnTypes := wireColumnTypes(execution.result)
  739. formats, formatErr := c.resolveResultFormats(portal.resultFormats, columnTypes, len(execution.result.Columns))
  740. if formatErr != nil {
  741. return &executeError{code: resultFormatSQLState(formatErr), err: formatErr}
  742. }
  743. execution.columnTypes = columnTypes
  744. execution.oids = c.resultColumnOIDs(columnTypes, len(execution.result.Columns))
  745. execution.formats = formats
  746. portal.execution = execution
  747. return nil
  748. }
  749. // classifyExecuteError maps a statement execution error to the SQLSTATE the
  750. // client receives and leaves the transaction state consistent.
  751. func (c *Connection) classifyExecuteError(stmt parser.Statement, err error) *executeError {
  752. code := ErrCodeInternalError
  753. var primaryKeyErr *storage.PrimaryKeyViolationError
  754. var uniqueErr *storage.UniqueViolationError
  755. var notNullErr *storage.NotNullViolationError
  756. var checkErr *storage.CheckViolationError
  757. var foreignKeyErr *storage.ForeignKeyViolationError
  758. if errors.Is(err, storage.ErrSerialization) {
  759. code = ErrCodeSerializationFailure
  760. c.txStatus = TxStatusIdle
  761. } else if errors.Is(err, pgerror.ErrLockNotAvailable) {
  762. code = ErrCodeLockNotAvailable
  763. if c.txStatus == TxStatusInBlock {
  764. c.txStatus = TxStatusFailed
  765. }
  766. } else if errors.Is(err, pgerror.ErrDeadlockDetected) {
  767. code = ErrCodeDeadlockDetected
  768. if c.txStatus == TxStatusInBlock {
  769. c.txStatus = TxStatusFailed
  770. }
  771. } else if errors.Is(err, pgerror.ErrInvalidText) {
  772. code = ErrCodeInvalidText
  773. if c.txStatus == TxStatusInBlock {
  774. c.txStatus = TxStatusFailed
  775. }
  776. } else if errors.Is(err, pgerror.ErrInvalidParameter) {
  777. code = ErrCodeInvalidParameter
  778. if c.txStatus == TxStatusInBlock {
  779. c.txStatus = TxStatusFailed
  780. }
  781. } else if errors.Is(err, pgerror.ErrDatatypeMismatch) {
  782. code = ErrCodeDatatypeMismatch
  783. if c.txStatus == TxStatusInBlock {
  784. c.txStatus = TxStatusFailed
  785. }
  786. } else if errors.Is(err, pgerror.ErrInvalidColumnReference) {
  787. code = ErrCodeInvalidColumnReference
  788. if c.txStatus == TxStatusInBlock {
  789. c.txStatus = TxStatusFailed
  790. }
  791. } else if errors.Is(err, pgerror.ErrUndefinedTable) || analysisUndefinedTable(err) {
  792. code = ErrCodeUndefinedTable
  793. if c.txStatus == TxStatusInBlock {
  794. c.txStatus = TxStatusFailed
  795. }
  796. } else if analysisTypeMismatch(err) {
  797. code = ErrCodeDatatypeMismatch
  798. if c.txStatus == TxStatusInBlock {
  799. c.txStatus = TxStatusFailed
  800. }
  801. } else if errors.As(err, &notNullErr) {
  802. code = "23502"
  803. if _, commit := stmt.(*parser.CommitStmt); commit {
  804. c.txStatus = TxStatusIdle
  805. } else if c.txStatus == TxStatusInBlock {
  806. c.txStatus = TxStatusFailed
  807. }
  808. } else if errors.As(err, &checkErr) {
  809. code = ErrCodeCheckViolation
  810. if _, commit := stmt.(*parser.CommitStmt); commit {
  811. c.txStatus = TxStatusIdle
  812. } else if c.txStatus == TxStatusInBlock {
  813. c.txStatus = TxStatusFailed
  814. }
  815. } else if errors.As(err, &foreignKeyErr) {
  816. code = ErrCodeForeignKeyViolation
  817. if _, commit := stmt.(*parser.CommitStmt); commit {
  818. c.txStatus = TxStatusIdle
  819. } else if c.txStatus == TxStatusInBlock {
  820. c.txStatus = TxStatusFailed
  821. }
  822. } else if errors.As(err, &uniqueErr) || errors.As(err, &primaryKeyErr) {
  823. code = ErrCodeUniqueViolation
  824. if _, commit := stmt.(*parser.CommitStmt); commit {
  825. c.txStatus = TxStatusIdle
  826. } else if c.txStatus == TxStatusInBlock {
  827. c.txStatus = TxStatusFailed
  828. }
  829. } else if errors.Is(err, pgerror.ErrFeatureNotSupported) || errors.Is(err, executor.ErrUnsupportedFeature) {
  830. code = ErrCodeFeatureNotSupported
  831. if c.txStatus == TxStatusInBlock {
  832. c.txStatus = TxStatusFailed
  833. }
  834. } else if _, commit := stmt.(*parser.CommitStmt); commit {
  835. c.txStatus = TxStatusIdle
  836. } else if c.txStatus == TxStatusInBlock {
  837. c.txStatus = TxStatusFailed
  838. }
  839. if uniqueErr != nil {
  840. return &executeError{code: code, err: fmt.Errorf("execution error: UNIQUE constraint failed: %s", uniqueErr.Constraint)}
  841. }
  842. return &executeError{code: code, err: fmt.Errorf("execution error: %w", err)}
  843. }
  844. // sendPortalRows writes one Execute response from the portal's materialized
  845. // result. The RowDescription is sent once, by the first Execute that has
  846. // columns, so a resumed Execute emits only DataRows. With maxRows > 0 the
  847. // response is PortalSuspended once the limit was reached; PostgreSQL reports
  848. // PortalSuspended even when the last row falls exactly on the limit and
  849. // completes on the next Execute, which is what this does too.
  850. func (c *Connection) sendPortalRows(portal *portal, maxRows int32) error {
  851. execution := portal.execution
  852. if len(execution.result.Columns) > 0 && !execution.described {
  853. if err := c.sendRowDescriptionFormats(execution.result.Columns, execution.columnTypes, execution.oids, execution.formats); err != nil {
  854. return err
  855. }
  856. execution.described = true
  857. }
  858. remaining := len(execution.result.Rows) - execution.rowOffset
  859. limit := remaining
  860. if maxRows > 0 && int(maxRows) < remaining {
  861. limit = int(maxRows)
  862. }
  863. for i := 0; i < limit; i++ {
  864. if err := c.sendDataRowFormats(execution.result.Rows[execution.rowOffset+i], execution.oids, execution.formats); err != nil {
  865. return c.failBinaryEncode(err)
  866. }
  867. }
  868. execution.rowOffset += limit
  869. if maxRows > 0 && limit == int(maxRows) {
  870. return c.sendPortalSuspended()
  871. }
  872. firstCompletion := !execution.completed
  873. execution.completed = true
  874. if err := c.sendCommandComplete(execution.commandTag); err != nil {
  875. return err
  876. }
  877. if firstCompletion && execution.result.LSN > 0 {
  878. if err := c.sendLSN(execution.result.LSN); err != nil {
  879. return err
  880. }
  881. }
  882. // The portal is exhausted: keep its metadata for a repeated Execute, but
  883. // release the row data so a transaction that leaves portals open does not
  884. // retain every result.
  885. execution.result.Rows = nil
  886. execution.rowOffset = 0
  887. return nil
  888. }
  889. func (c *Connection) sendTabularResult(result *executor.Result, tag string, bindFormats []int16) error {
  890. formats, err := c.resolveResultFormats(bindFormats, result.ColumnTypes, len(result.Columns))
  891. if err != nil {
  892. return c.failResultFormat(err)
  893. }
  894. oids := c.resultColumnOIDs(result.ColumnTypes, len(result.Columns))
  895. if err := c.sendRowDescriptionFormats(result.Columns, result.ColumnTypes, oids, formats); err != nil {
  896. return err
  897. }
  898. for _, row := range result.Rows {
  899. if err := c.sendDataRowFormats(row, oids, formats); err != nil {
  900. return c.failBinaryEncode(err)
  901. }
  902. }
  903. return c.sendCommandComplete(fmt.Sprintf("%s %d", tag, len(result.Rows)))
  904. }
  905. func (c *Connection) handleClose(msg *Message) error {
  906. if c.extendedFailed {
  907. return nil
  908. }
  909. if len(msg.Data) < 2 {
  910. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close message"))
  911. }
  912. name, pos, err := readCString(msg.Data, 1)
  913. if err != nil || pos != len(msg.Data) {
  914. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close name"))
  915. }
  916. if msg.Data[0] == 'S' {
  917. delete(c.statements, name)
  918. } else if msg.Data[0] == 'P' {
  919. delete(c.portals, name)
  920. } else {
  921. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close target"))
  922. }
  923. return c.writeMessage(MsgCloseComplete, nil)
  924. }
  925. // clearPortals drops every portal. PostgreSQL binds a portal to the transaction
  926. // that created it: Sync ends the implicit transaction outside an explicit
  927. // block, and COMMIT/ROLLBACK end an explicit one. Prepared statements are not
  928. // affected, so a client re-binds after the transaction ends.
  929. func (c *Connection) clearPortals() {
  930. clear(c.portals)
  931. }
  932. // resetsPortals reports whether stmt invalidates every open portal. COMMIT and
  933. // ROLLBACK end the transaction, and ROLLBACK TO SAVEPOINT undoes writes a
  934. // suspended portal may already have materialized: resuming it would stream rows
  935. // and a completion tag from a removed state. Clearing every portal on ROLLBACK
  936. // TO SAVEPOINT is stricter than PostgreSQL, which keeps portals created before
  937. // the savepoint; the coarse rule is what keeps a failed or rewound statement
  938. // from leaking into a resumed stream.
  939. func resetsPortals(stmt parser.Statement) bool {
  940. switch stmt.(type) {
  941. case *parser.CommitStmt, *parser.RollbackStmt:
  942. return true
  943. }
  944. return false
  945. }
  946. func (c *Connection) failExtended(code string, err error) error {
  947. c.extendedFailed = true
  948. if c.txStatus == TxStatusInBlock {
  949. c.txStatus = TxStatusFailed
  950. }
  951. return c.sendError("ERROR", code, err.Error())
  952. }
  953. func (c *Connection) handleProxyError(msg *Message) error {
  954. if len(msg.Data) != 1 || (msg.Data[0] != MsgQuery && msg.Data[0] != MsgParse) {
  955. _ = c.sendError("FATAL", ErrCodeProtocolViolation, "invalid proxy error relay")
  956. return io.EOF
  957. }
  958. code, message := "42501", "permission denied by API key scopes"
  959. if c.txStatus == TxStatusFailed {
  960. code, message = ErrCodeTransactionAborted, "current transaction is aborted, commands ignored until end of transaction block"
  961. }
  962. if msg.Data[0] == MsgParse {
  963. c.extendedCycle = true
  964. return c.failExtended(code, errors.New(message))
  965. }
  966. if c.txStatus == TxStatusInBlock {
  967. c.txStatus = TxStatusFailed
  968. }
  969. if err := c.sendError("ERROR", code, message); err != nil {
  970. return err
  971. }
  972. return c.sendReadyForQuery()
  973. }
  974. // analysisTypeMismatch reports whether the error is an analyzer type-mismatch,
  975. // which is reported with SQLSTATE 42804 instead of a generic internal error.
  976. func analysisTypeMismatch(err error) bool {
  977. var analysisErr *analyzer.AnalysisError
  978. return errors.As(err, &analysisErr) && analysisErr.Type == analyzer.ErrTypeMismatch
  979. }
  980. // analysisUndefinedTable reports whether the error is the analyzer's
  981. // table-not-found, which PostgreSQL reports as 42P01 (undefined_table).
  982. func analysisUndefinedTable(err error) bool {
  983. var analysisErr *analyzer.AnalysisError
  984. return errors.As(err, &analysisErr) && analysisErr.Type == analyzer.ErrTableNotFound
  985. }
  986. type boundParameter struct {
  987. value []byte
  988. oid int32
  989. format int16
  990. null bool
  991. }
  992. func readCString(data []byte, pos int) (string, int, error) {
  993. if pos < 0 || pos >= len(data) {
  994. return "", pos, fmt.Errorf("missing null-terminated string")
  995. }
  996. end := bytes.IndexByte(data[pos:], 0)
  997. if end < 0 {
  998. return "", pos, fmt.Errorf("unterminated string")
  999. }
  1000. return string(data[pos : pos+end]), pos + end + 1, nil
  1001. }
  1002. func readInt16List(data []byte, pos int) ([]int16, int, error) {
  1003. if pos+2 > len(data) {
  1004. return nil, pos, fmt.Errorf("missing list length")
  1005. }
  1006. count := int(binary.BigEndian.Uint16(data[pos : pos+2]))
  1007. pos += 2
  1008. if pos+count*2 > len(data) {
  1009. return nil, pos, fmt.Errorf("truncated list")
  1010. }
  1011. result := make([]int16, count)
  1012. for i := range result {
  1013. result[i] = int16(binary.BigEndian.Uint16(data[pos : pos+2]))
  1014. pos += 2
  1015. }
  1016. return result, pos, nil
  1017. }
  1018. func parameterOID(oids []int32, index int) int32 {
  1019. if index < len(oids) {
  1020. return oids[index]
  1021. }
  1022. return 0
  1023. }
  1024. func parameterFormat(formats []int16, index int) int16 {
  1025. if len(formats) == 1 {
  1026. return formats[0]
  1027. }
  1028. if index < len(formats) {
  1029. return formats[index]
  1030. }
  1031. return 0
  1032. }
  1033. func bindQuery(query string, params []boundParameter) (string, error) {
  1034. var result strings.Builder
  1035. last := 0
  1036. for _, reference := range scanParameters(query) {
  1037. result.WriteString(query[last:reference.start])
  1038. if reference.number < 1 || reference.number > len(params) {
  1039. return "", fmt.Errorf("parameter %s was not provided", query[reference.start:reference.end])
  1040. }
  1041. literal, err := parameterLiteral(params[reference.number-1])
  1042. if err != nil {
  1043. return "", fmt.Errorf("parameter $%d: %w", reference.number, err)
  1044. }
  1045. // Mark substituted parameters so result-type inference does not treat
  1046. // them as user-written constants. A cast over a parameter must keep the
  1047. // carrier type instead of narrowing to the literal's width.
  1048. result.WriteString("pizzasql_param(")
  1049. result.WriteString(literal)
  1050. result.WriteString(")")
  1051. last = reference.end
  1052. }
  1053. result.WriteString(query[last:])
  1054. return result.String(), nil
  1055. }
  1056. func parameterLiteral(param boundParameter) (string, error) {
  1057. if param.null {
  1058. return "NULL", nil
  1059. }
  1060. if param.format == 1 {
  1061. if element, isArray := arrayParamElementType(param.oid); isArray {
  1062. return binaryArrayLiteral(element, param.value)
  1063. }
  1064. if param.oid == 3802 {
  1065. // PostgreSQL's binary jsonb format is a version byte followed by the
  1066. // document text. pgx sends this form by default.
  1067. if len(param.value) == 0 {
  1068. return "", pgerror.InvalidText("jsonb binary parameter is empty")
  1069. }
  1070. if param.value[0] != 1 {
  1071. return "", pgerror.InvalidText("unsupported jsonb binary format version %d", param.value[0])
  1072. }
  1073. canonical, err := executor.CanonicalizeJSONB(string(param.value[1:]))
  1074. if err != nil {
  1075. return "", err
  1076. }
  1077. return "'" + strings.ReplaceAll(canonical, "'", "''") + "'::jsonb", nil
  1078. }
  1079. switch param.oid {
  1080. case 700, 701:
  1081. return binaryFloatText(param.oid, param.value)
  1082. case 1700:
  1083. return binaryNumericText(param.value)
  1084. case 16:
  1085. if len(param.value) != 1 || param.value[0] > 1 {
  1086. return "", pgerror.InvalidText("invalid binary boolean parameter")
  1087. }
  1088. if param.value[0] == 0 {
  1089. return "FALSE", nil
  1090. }
  1091. return "TRUE", nil
  1092. case 21:
  1093. if len(param.value) != 2 {
  1094. return "", fmt.Errorf("invalid binary int2")
  1095. }
  1096. return strconv.FormatInt(int64(int16(binary.BigEndian.Uint16(param.value))), 10), nil
  1097. case 23:
  1098. if len(param.value) != 4 {
  1099. return "", fmt.Errorf("invalid binary int4")
  1100. }
  1101. return strconv.FormatInt(int64(int32(binary.BigEndian.Uint32(param.value))), 10), nil
  1102. case 20:
  1103. if len(param.value) != 8 {
  1104. return "", fmt.Errorf("invalid binary int8")
  1105. }
  1106. return strconv.FormatInt(int64(binary.BigEndian.Uint64(param.value)), 10), nil
  1107. default:
  1108. return "", fmt.Errorf("%w: binary parameter format for OID %d", pgerror.ErrFeatureNotSupported, param.oid)
  1109. }
  1110. }
  1111. value := string(param.value)
  1112. if param.oid == 3802 {
  1113. // A text-format jsonb parameter is canonicalized at Bind, so the executor
  1114. // receives the same bytes a jsonb column stores and an invalid document
  1115. // fails before execution.
  1116. canonical, err := executor.CanonicalizeJSONB(value)
  1117. if err != nil {
  1118. return "", err
  1119. }
  1120. return "'" + strings.ReplaceAll(canonical, "'", "''") + "'::jsonb", nil
  1121. }
  1122. if element, isArray := arrayParamElementType(param.oid); isArray {
  1123. // The bound value is PostgreSQL array text. Validate and canonicalize it
  1124. // now so a malformed array fails at Bind instead of during row
  1125. // evaluation, then emit a typed literal the executor accepts unchanged.
  1126. arrayType := element + "[]"
  1127. canonical, err := executor.CanonicalizeArrayText(value, arrayType)
  1128. if err != nil {
  1129. return "", err
  1130. }
  1131. return "'" + strings.ReplaceAll(canonical, "'", "''") + "'::" + arrayType, nil
  1132. }
  1133. switch param.oid {
  1134. case 0:
  1135. if strings.EqualFold(value, "true") || strings.EqualFold(value, "false") {
  1136. return strings.ToUpper(value), nil
  1137. }
  1138. if _, err := strconv.ParseFloat(value, 64); err == nil && value != "" {
  1139. return value, nil
  1140. }
  1141. return "'" + strings.ReplaceAll(value, "'", "''") + "'", nil
  1142. case 16:
  1143. if strings.EqualFold(value, "true") || value == "1" || value == "t" {
  1144. return "TRUE", nil
  1145. }
  1146. return "FALSE", nil
  1147. case 20, 21, 23, 26, 700, 701, 1700:
  1148. if _, err := strconv.ParseFloat(value, 64); err != nil {
  1149. return "", fmt.Errorf("invalid numeric value")
  1150. }
  1151. return value, nil
  1152. default:
  1153. return "'" + strings.ReplaceAll(value, "'", "''") + "'", nil
  1154. }
  1155. }
  1156. // sendResult sends a statement's result. columnTypes are the types reported in
  1157. // RowDescription (already corrected for BLOB values) and formats are the
  1158. // portal's resolved per-column format codes, or nil for all-text results.
  1159. func (c *Connection) sendResult(result *executor.Result, stmt parser.Statement, columnTypes []string, formats []int16) error {
  1160. // Any statement that produced a row set (SELECT, or INSERT/UPDATE/DELETE
  1161. // with RETURNING) sends a row description and its data rows. Other
  1162. // statements only send the command completion tag.
  1163. if len(result.Columns) > 0 {
  1164. oids := c.resultColumnOIDs(columnTypes, len(result.Columns))
  1165. if err := c.sendRowDescriptionFormats(result.Columns, columnTypes, oids, formats); err != nil {
  1166. return err
  1167. }
  1168. for _, row := range result.Rows {
  1169. if err := c.sendDataRowFormats(row, oids, formats); err != nil {
  1170. return c.failBinaryEncode(err)
  1171. }
  1172. }
  1173. return c.sendCommandComplete(c.getCommandTag(stmt, result))
  1174. }
  1175. // For other statements, just send command complete
  1176. tag := c.getCommandTag(stmt, result)
  1177. return c.sendCommandComplete(tag)
  1178. }
  1179. // wireColumnTypes corrects declared-affinity metadata when SQLite has stored a
  1180. // value of another type. In particular, binding []byte to a VARCHAR column is
  1181. // still a BLOB in SQLite; advertising TEXT while encoding PostgreSQL bytea text
  1182. // would make clients receive the literal "\\x..." instead of the original
  1183. // bytes.
  1184. func wireColumnTypes(result *executor.Result) []string {
  1185. types := append([]string(nil), result.ColumnTypes...)
  1186. if len(types) < len(result.Columns) {
  1187. types = append(types, make([]string, len(result.Columns)-len(types))...)
  1188. }
  1189. for _, row := range result.Rows {
  1190. for i, value := range row {
  1191. if i >= len(types) {
  1192. break
  1193. }
  1194. if _, ok := value.([]byte); ok {
  1195. types[i] = "BLOB"
  1196. }
  1197. }
  1198. }
  1199. return types
  1200. }
  1201. // getCommandTag returns the command completion tag
  1202. func (c *Connection) getCommandTag(stmt parser.Statement, result *executor.Result) string {
  1203. switch s := stmt.(type) {
  1204. case *parser.SelectStmt:
  1205. return fmt.Sprintf("SELECT %d", len(result.Rows))
  1206. case *parser.CreateTableStmt:
  1207. return "CREATE TABLE"
  1208. case *parser.DropTableStmt:
  1209. return "DROP TABLE"
  1210. case *parser.CreateIndexStmt:
  1211. return "CREATE INDEX"
  1212. case *parser.DropIndexStmt:
  1213. return "DROP INDEX"
  1214. case *parser.AlterTableStmt:
  1215. return "ALTER TABLE"
  1216. case *parser.InsertStmt:
  1217. return fmt.Sprintf("INSERT 0 %d", result.RowsAffected)
  1218. case *parser.UpdateStmt:
  1219. return fmt.Sprintf("UPDATE %d", result.RowsAffected)
  1220. case *parser.DeleteStmt:
  1221. return fmt.Sprintf("DELETE %d", result.RowsAffected)
  1222. case *parser.BeginStmt:
  1223. c.txStatus = TxStatusInBlock
  1224. return "BEGIN"
  1225. case *parser.CommitStmt:
  1226. c.txStatus = TxStatusIdle
  1227. return "COMMIT"
  1228. case *parser.RollbackStmt:
  1229. if s.Savepoint != "" {
  1230. c.txStatus = TxStatusInBlock
  1231. return "ROLLBACK"
  1232. }
  1233. c.txStatus = TxStatusIdle
  1234. return "ROLLBACK"
  1235. case *parser.SavepointStmt:
  1236. c.txStatus = TxStatusInBlock
  1237. return "SAVEPOINT"
  1238. case *parser.ReleaseStmt:
  1239. c.txStatus = TxStatusInBlock
  1240. return "RELEASE"
  1241. case *parser.ListenStmt:
  1242. return "LISTEN"
  1243. case *parser.UnlistenStmt:
  1244. return "UNLISTEN"
  1245. case *parser.NotifyStmt:
  1246. return "NOTIFY"
  1247. default:
  1248. return "OK"
  1249. }
  1250. }
  1251. // sendAuthenticationOk sends authentication OK message
  1252. func (c *Connection) sendAuthenticationOk() error {
  1253. mb := NewMessageBuilder()
  1254. mb.WriteInt32(0) // Auth OK
  1255. return c.writeMessage(MsgAuthenticationOk, mb.Bytes())
  1256. }
  1257. // drainNotifications writes every notification currently buffered for this
  1258. // session. It is called at protocol-safe points (after Sync/ReadyForQuery).
  1259. func (c *Connection) drainNotifications() error {
  1260. ch := c.executor.NotificationChannel()
  1261. for {
  1262. select {
  1263. case n := <-ch:
  1264. if err := c.sendNotification(n); err != nil {
  1265. return err
  1266. }
  1267. default:
  1268. return c.writer.Flush()
  1269. }
  1270. }
  1271. }
  1272. // sendNotification writes a NotificationResponse frame. The frame is only
  1273. // written by the connection's main goroutine, never from a publisher.
  1274. func (c *Connection) sendNotification(n storage.Notification) error {
  1275. mb := NewMessageBuilder()
  1276. mb.WriteInt32(n.PID)
  1277. mb.WriteString(n.Channel)
  1278. mb.WriteString(n.Payload)
  1279. return c.writeMessage(MsgNotificationResponse, mb.Bytes())
  1280. }
  1281. // sendLSN exposes the last commit LSN as a ParameterStatus. Drivers that do
  1282. // not know the key ignore it; subscribers can use it as an ordering cursor.
  1283. func (c *Connection) sendLSN(lsn uint64) error {
  1284. return c.sendParameterStatus("pizzasql.lsn", strconv.FormatUint(lsn, 10))
  1285. }
  1286. // sendParameterStatus sends a parameter status message
  1287. func (c *Connection) sendParameterStatus(name, value string) error {
  1288. mb := NewMessageBuilder()
  1289. mb.WriteString(name)
  1290. mb.WriteString(value)
  1291. return c.writeMessage(MsgParameterStatus, mb.Bytes())
  1292. }
  1293. // sendBackendKeyData sends backend key data
  1294. func (c *Connection) sendBackendKeyData(processID, secretKey int32) error {
  1295. mb := NewMessageBuilder()
  1296. mb.WriteInt32(processID)
  1297. mb.WriteInt32(secretKey)
  1298. return c.writeMessage(MsgBackendKeyData, mb.Bytes())
  1299. }
  1300. // isIdleRollback reports whether a bare ROLLBACK found no transaction to roll
  1301. // back. A COMMIT rejected by storage has already ended the transaction, so the
  1302. // client's cleanup ROLLBACK must complete (PostgreSQL reports a warning and
  1303. // succeeds) instead of surfacing an internal error on an idle session.
  1304. func isIdleRollback(stmt parser.Statement, status byte, err error) bool {
  1305. rollback, ok := stmt.(*parser.RollbackStmt)
  1306. if !ok || rollback.Savepoint != "" {
  1307. return false
  1308. }
  1309. return status == TxStatusIdle && errors.Is(err, executor.ErrNoTransaction)
  1310. }
  1311. // sendReadyForQuery sends ready for query message
  1312. func (c *Connection) sendReadyForQuery() error {
  1313. if c.txStatus == TxStatusIdle {
  1314. // The transaction this cycle ran in ends here, so its portals do too.
  1315. // A portal inside an explicit block survives (status T) until
  1316. // COMMIT/ROLLBACK, and a failed block (status E) keeps its portals so
  1317. // Execute still reports 25P02 until the transaction is rolled back.
  1318. c.clearPortals()
  1319. }
  1320. mb := NewMessageBuilder()
  1321. mb.AppendByte(c.txStatus)
  1322. if err := c.writeMessage(MsgReadyForQuery, mb.Bytes()); err != nil {
  1323. return err
  1324. }
  1325. // ReadyForQuery closes out a response cycle, so flush everything buffered
  1326. // so far. This is what makes simple-query results and Sync responses
  1327. // visible to the client.
  1328. return c.writer.Flush()
  1329. }
  1330. // sendEmptyQueryResponse sends empty query response
  1331. func (c *Connection) sendEmptyQueryResponse() error {
  1332. return c.writeMessage(MsgEmptyQueryResponse, []byte{})
  1333. }
  1334. // sendParameterDescription reports the negotiated parameter types of a
  1335. // prepared statement. The protocol count field is 16-bit and the negotiated
  1336. // list never exceeds maxParameterNumber, so the conversion cannot lose a count.
  1337. func (c *Connection) sendParameterDescription(oids []int32) error {
  1338. if len(oids) > maxParameterNumber {
  1339. return fmt.Errorf("parameter description has %d entries; the protocol limit is %d", len(oids), maxParameterNumber)
  1340. }
  1341. mb := NewMessageBuilder()
  1342. mb.WriteInt16(int16(uint16(len(oids))))
  1343. for _, oid := range oids {
  1344. mb.WriteInt32(oid)
  1345. }
  1346. return c.writeMessage(MsgParameterDescription, mb.Bytes())
  1347. }
  1348. // sendRowDescription sends row description (column metadata) in text format.
  1349. func (c *Connection) sendRowDescription(columns []string, columnTypes []string) error {
  1350. return c.sendRowDescriptionFormats(columns, columnTypes, c.resultColumnOIDs(columnTypes, len(columns)), nil)
  1351. }
  1352. // sendRowDescriptionFormats sends row description with the per-column formats a
  1353. // portal resolved at Bind. PostgreSQL reports the bound formats in a portal
  1354. // RowDescription; this server emits its RowDescription at Execute instead of
  1355. // Describe, so the portal's formats travel with the row metadata. OIDs are the
  1356. // same for text and binary results.
  1357. func (c *Connection) sendRowDescriptionFormats(columns []string, columnTypes []string, oids []int32, formats []int16) error {
  1358. mb := NewMessageBuilder()
  1359. mb.WriteInt16(int16(len(columns)))
  1360. for i, col := range columns {
  1361. colType := typeNameAt(columnTypes, i)
  1362. format := int16(0)
  1363. if i < len(formats) {
  1364. format = formats[i]
  1365. }
  1366. mb.WriteString(col)
  1367. mb.WriteInt32(0) // table OID
  1368. mb.WriteInt16(0) // column attribute number
  1369. mb.WriteInt32(oids[i]) // type OID
  1370. mb.WriteInt16(c.getTypeSizeForType(colType)) // type size
  1371. mb.WriteInt32(-1) // type modifier
  1372. mb.WriteInt16(format) // format code
  1373. }
  1374. return c.writeMessage(MsgRowDescription, mb.Bytes())
  1375. }
  1376. // resultColumnOIDs returns the PostgreSQL OID reported for every result column.
  1377. func (c *Connection) resultColumnOIDs(columnTypes []string, columnCount int) []int32 {
  1378. oids := make([]int32, columnCount)
  1379. for i := range oids {
  1380. oids[i] = c.getOIDForType(typeNameAt(columnTypes, i))
  1381. }
  1382. return oids
  1383. }
  1384. // sendDataRow sends a data row in text format
  1385. func (c *Connection) sendDataRow(row []interface{}, columns []string) error {
  1386. return c.sendDataRowFormats(row, nil, nil)
  1387. }
  1388. // sendDataRowFormats sends one DataRow, choosing text or binary encoding per
  1389. // column from formats. NULL is always length -1. Binary values are appended
  1390. // directly into the DataRow buffer; a value that cannot be encoded fails before
  1391. // the row is written, so the client never receives a partial DataRow.
  1392. func (c *Connection) sendDataRowFormats(row []interface{}, oids []int32, formats []int16) error {
  1393. mb := NewMessageBuilder()
  1394. mb.WriteInt16(int16(len(row)))
  1395. for i, value := range row {
  1396. if value == nil {
  1397. mb.WriteInt32(-1) // NULL indicator
  1398. continue
  1399. }
  1400. format := int16(0)
  1401. if i < len(formats) {
  1402. format = formats[i]
  1403. }
  1404. if format == 0 {
  1405. strValue := c.valueToString(value)
  1406. mb.WriteInt32(int32(len(strValue)))
  1407. mb.WriteBytes([]byte(strValue))
  1408. continue
  1409. }
  1410. oid := int32(25) // TEXT, the fallback RowDescription OID
  1411. if i < len(oids) {
  1412. oid = oids[i]
  1413. }
  1414. err := mb.AppendBinary(func(dst []byte) ([]byte, error) {
  1415. return appendBinaryResultValue(dst, oid, value)
  1416. })
  1417. if err != nil {
  1418. return fmt.Errorf("binary result column %d: %w", i+1, err)
  1419. }
  1420. }
  1421. return c.writeMessage(MsgDataRow, mb.Bytes())
  1422. }
  1423. // sendCommandComplete sends command complete message
  1424. func (c *Connection) sendCommandComplete(tag string) error {
  1425. mb := NewMessageBuilder()
  1426. mb.WriteString(tag)
  1427. return c.writeMessage(MsgCommandComplete, mb.Bytes())
  1428. }
  1429. // sendPortalSuspended reports that a bounded Execute stopped at its row limit
  1430. // with rows left to fetch.
  1431. func (c *Connection) sendPortalSuspended() error {
  1432. return c.writeMessage(MsgPortalSuspended, nil)
  1433. }
  1434. // sendError sends an error response
  1435. func (c *Connection) sendError(severity, code, message string) error {
  1436. if severity == "ERROR" && c.txStatus == TxStatusInBlock {
  1437. c.txStatus = TxStatusFailed
  1438. }
  1439. mb := NewMessageBuilder()
  1440. mb.AppendByte(ErrorFieldSeverity)
  1441. mb.WriteString(severity)
  1442. mb.AppendByte(ErrorFieldCode)
  1443. mb.WriteString(code)
  1444. mb.AppendByte(ErrorFieldMessage)
  1445. mb.WriteString(message)
  1446. mb.AppendByte(0) // Terminator
  1447. if err := c.writeMessage(MsgErrorResponse, mb.Bytes()); err != nil {
  1448. return err
  1449. }
  1450. // Errors must be visible promptly, including FATAL startup failures that
  1451. // are not followed by a ReadyForQuery before the connection closes.
  1452. return c.writer.Flush()
  1453. }
  1454. // writeMessage buffers a message for the connection. It does not flush, so
  1455. // callers that need to make a response visible to the client must flush at the
  1456. // appropriate protocol boundary (ReadyForQuery, an explicit Flush message, or
  1457. // an error response). Buffering amortizes the per-message syscalls that a
  1458. // result set would otherwise incur; the underlying bufio.Writer bounds memory
  1459. // use so large result sets cannot grow the buffer without limit.
  1460. func (c *Connection) writeMessage(msgType byte, data []byte) error {
  1461. if !c.quiet {
  1462. log.Printf("Sending message type=%c length=%d", msgType, len(data)+4)
  1463. }
  1464. return WriteMessage(c.writer, msgType, data)
  1465. }
  1466. // arrayElementTypeName reports the element type of an array type name such as
  1467. // "INTEGER[]". It reports false for scalar type names.
  1468. func arrayElementTypeName(typeName string) (string, bool) {
  1469. upper := strings.ToUpper(strings.TrimSpace(typeName))
  1470. if !strings.HasSuffix(upper, "[]") {
  1471. return "", false
  1472. }
  1473. return strings.TrimSpace(strings.TrimSuffix(upper, "[]")), true
  1474. }
  1475. // arrayOIDForElement maps an array element type name to its PostgreSQL array
  1476. // OID. Narrower integer types report int8[] because values are not
  1477. // range-checked, matching the scalar carrier rule; NUMERIC reports numeric[]
  1478. // because array elements stay text.
  1479. func arrayOIDForElement(element string) int32 {
  1480. base := strings.ToUpper(strings.TrimSpace(element))
  1481. if idx := strings.IndexByte(base, '('); idx >= 0 {
  1482. base = strings.TrimSpace(base[:idx])
  1483. }
  1484. switch base {
  1485. case "INTEGER", "INT", "INT4":
  1486. return 1007 // INT4ARRAYOID
  1487. case "BIGINT", "INT8", "SMALLINT", "INT2", "TINYINT", "MEDIUMINT":
  1488. return 1016 // INT8ARRAYOID
  1489. case "BOOLEAN", "BOOL":
  1490. return 1000 // BOOLARRAYOID
  1491. case "REAL", "FLOAT", "FLOAT4":
  1492. return 1021 // FLOAT4ARRAYOID
  1493. case "DOUBLE", "DOUBLE PRECISION", "FLOAT8":
  1494. return 1022 // FLOAT8ARRAYOID
  1495. case "NUMERIC", "DECIMAL":
  1496. return 1231 // NUMERICARRAYOID
  1497. case "VARCHAR", "NVARCHAR", "CHARACTER VARYING":
  1498. return 1015 // VARCHARARRAYOID
  1499. default:
  1500. return 1009 // TEXTARRAYOID
  1501. }
  1502. }
  1503. // arrayParamElementType maps an array parameter OID to the element type the
  1504. // bound literal is cast to. Unknown OIDs are handled by callers.
  1505. func arrayParamElementType(oid int32) (string, bool) {
  1506. switch oid {
  1507. case 1009:
  1508. return "TEXT", true
  1509. case 1015:
  1510. return "VARCHAR", true
  1511. case 1007:
  1512. return "INTEGER", true
  1513. case 1016:
  1514. return "BIGINT", true
  1515. case 1005:
  1516. return "SMALLINT", true
  1517. case 1000:
  1518. return "BOOLEAN", true
  1519. case 1021:
  1520. return "REAL", true
  1521. case 1022:
  1522. return "DOUBLE", true
  1523. case 1231:
  1524. return "NUMERIC", true
  1525. default:
  1526. return "", false
  1527. }
  1528. }
  1529. // getOIDForType returns PostgreSQL OID for type.
  1530. //
  1531. // Types narrower than the value the engine carries are reported as the carrier
  1532. // type, because the engine does not range-check stored or cast values: a value
  1533. // that does not fit int2/int4 or float4 would fail client-side decoding rather
  1534. // than having been rejected on write. INTEGER and REAL keep their declared
  1535. // mappings, which predate this rule and are what existing clients expect.
  1536. func (c *Connection) getOIDForType(typeName string) int32 {
  1537. if element, ok := arrayElementTypeName(typeName); ok {
  1538. return arrayOIDForElement(element)
  1539. }
  1540. switch strings.ToUpper(typeName) {
  1541. case "INT2":
  1542. // The executor's exact-width spelling for a SMALLINT cast whose
  1543. // constant value fits int2. A SMALLINT column is grouped below because
  1544. // its stored values are not range-checked.
  1545. return 21 // INT2OID
  1546. case "SMALLINT", "TINYINT", "MEDIUMINT":
  1547. // Carried as int64 and not range-checked, so int8 is the honest type.
  1548. return 20 // INT8OID
  1549. case "INTEGER", "INT", "INT4":
  1550. return 23 // INT4OID
  1551. case "BIGINT", "INT8":
  1552. return 20 // INT8OID
  1553. case "NUMERIC", "DECIMAL":
  1554. // Values round-trip through JSON as float64; there is no exact decimal
  1555. // carrier, so NUMERIC is not advertised.
  1556. return 701 // FLOAT8OID
  1557. case "JSONB":
  1558. return 3802 // JSONBOID
  1559. case "OID":
  1560. return 26 // OIDOID
  1561. case "REGCLASS":
  1562. return 2205 // REGCLASSOID
  1563. case "REGTYPE":
  1564. return 2206 // REGTYPEOID
  1565. case "REGPROC":
  1566. // pg_type.typinput and friends are regproc attributes.
  1567. return 24 // REGPROCOID
  1568. case "NAME":
  1569. return 19 // NAMEOID
  1570. case "TEXT", "VARCHAR", "CHAR", "UUID":
  1571. // UUID is stored as text (SQLite-style), so it reports TEXTOID rather
  1572. // than the native PG UUID OID.
  1573. return 25 // TEXTOID
  1574. case "REAL", "FLOAT", "FLOAT4":
  1575. return 700 // FLOAT4OID
  1576. case "DOUBLE", "FLOAT8":
  1577. return 701 // FLOAT8OID
  1578. case "BOOLEAN", "BOOL":
  1579. return 16 // BOOLOID
  1580. case "BLOB":
  1581. return 17 // BYTEAOID
  1582. case "DATETIME", "TIMESTAMP":
  1583. // Datetime values are exchanged as UTC RFC3339 (ISO8601 with a timezone
  1584. // offset), which timestamptz decodes directly.
  1585. return 1184 // TIMESTAMPTZOID
  1586. case "DATE":
  1587. return 1082 // DATEOID
  1588. default:
  1589. return 25 // Default to TEXT
  1590. }
  1591. }
  1592. // getTypeSizeForType returns type size in bytes, or -1 for variable length.
  1593. func (c *Connection) getTypeSizeForType(typeName string) int16 {
  1594. if _, ok := arrayElementTypeName(typeName); ok {
  1595. return -1 // arrays are variable length
  1596. }
  1597. switch strings.ToUpper(typeName) {
  1598. case "INT2":
  1599. return 2 // Exact int2 cast result; see getOIDForType.
  1600. case "SMALLINT", "TINYINT", "MEDIUMINT":
  1601. return 8 // Reported as int8; see getOIDForType.
  1602. case "INTEGER", "INT", "INT4":
  1603. return 4
  1604. case "BIGINT", "INT8":
  1605. return 8
  1606. case "NUMERIC", "DECIMAL":
  1607. return 8 // Reported as float8; see getOIDForType.
  1608. case "REAL", "FLOAT", "FLOAT4":
  1609. return 4
  1610. case "DOUBLE", "FLOAT8":
  1611. return 8
  1612. case "BOOLEAN", "BOOL":
  1613. return 1
  1614. case "DATETIME", "TIMESTAMP":
  1615. return 8
  1616. case "DATE":
  1617. return 4
  1618. case "OID", "REGCLASS", "REGTYPE", "REGPROC":
  1619. return 4
  1620. case "NAME":
  1621. return 64
  1622. default:
  1623. return -1 // Variable length
  1624. }
  1625. }
  1626. // valueToString converts a value to its PostgreSQL text representation
  1627. func (c *Connection) valueToString(value interface{}) string {
  1628. return textValueString(value)
  1629. }
  1630. // textValueString is the text representation the wire layer sends for a value.
  1631. // Binary text and bytea results reuse it so both formats carry the same bytes
  1632. // for values without a native binary form. PostgreSQL's text format for bytea is
  1633. // \x followed by hex, which lets libpq/pgx decode a BLOB column (OID 17)
  1634. // losslessly.
  1635. func textValueString(value interface{}) string {
  1636. if value == nil {
  1637. return ""
  1638. }
  1639. if b, ok := value.([]byte); ok {
  1640. return `\x` + hex.EncodeToString(b)
  1641. }
  1642. return fmt.Sprintf("%v", value)
  1643. }
  1644. // handleVersionQuery handles SELECT version()
  1645. func (c *Connection) handleVersionQuery() error {
  1646. columns := []string{"version"}
  1647. columnTypes := []string{"TEXT"}
  1648. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1649. return err
  1650. }
  1651. row := []interface{}{"PostgreSQL " + version.PostgreSQLCompatVersion + " (PizzaSQL)"}
  1652. if err := c.sendDataRow(row, columns); err != nil {
  1653. return err
  1654. }
  1655. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1656. return err
  1657. }
  1658. return c.sendReadyForQuery()
  1659. }
  1660. // handleCurrentUserQuery handles SELECT current_user
  1661. func (c *Connection) handleCurrentUserQuery() error {
  1662. columns := []string{"current_user"}
  1663. columnTypes := []string{"TEXT"}
  1664. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1665. return err
  1666. }
  1667. user := c.params["user"]
  1668. if user == "" {
  1669. user = "pizzasql"
  1670. }
  1671. row := []interface{}{user}
  1672. if err := c.sendDataRow(row, columns); err != nil {
  1673. return err
  1674. }
  1675. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1676. return err
  1677. }
  1678. return c.sendReadyForQuery()
  1679. }
  1680. // handleShowCommand handles SHOW commands
  1681. func (c *Connection) handleShowCommand(sqlUpper string) error {
  1682. var value string
  1683. var name string
  1684. if sqlUpper == "SERVER_VERSION" {
  1685. name = "server_version"
  1686. value = version.PostgreSQLCompatVersion
  1687. } else if sqlUpper == "SERVER_ENCODING" {
  1688. name = "server_encoding"
  1689. value = "UTF8"
  1690. } else if sqlUpper == "CLIENT_ENCODING" {
  1691. name = "client_encoding"
  1692. value = "UTF8"
  1693. } else {
  1694. // Unknown SHOW command
  1695. c.sendError("ERROR", ErrCodeFeatureNotSupported, "SHOW command not supported")
  1696. return c.sendReadyForQuery()
  1697. }
  1698. columns := []string{name}
  1699. columnTypes := []string{"TEXT"}
  1700. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1701. return err
  1702. }
  1703. row := []interface{}{value}
  1704. if err := c.sendDataRow(row, columns); err != nil {
  1705. return err
  1706. }
  1707. if err := c.sendCommandComplete("SHOW"); err != nil {
  1708. return err
  1709. }
  1710. return c.sendReadyForQuery()
  1711. }
  1712. // isRollbackStatement reports whether sql parses as a single ROLLBACK
  1713. // statement, including ROLLBACK TO SAVEPOINT.
  1714. func isRollbackStatement(sql string) bool {
  1715. stmt, err := parser.New(lexer.New(sql)).Parse()
  1716. if err != nil {
  1717. return false
  1718. }
  1719. _, ok := stmt.(*parser.RollbackStmt)
  1720. return ok
  1721. }