connection.go 55 KB

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