connection.go 55 KB

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