connection.go 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752
  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. // paramOIDs copies the bound statement's negotiated types so Describe
  69. // (Portal) reports the same ParameterDescription as Describe (Statement).
  70. paramOIDs []int32
  71. }
  72. // NewConnection creates a new connection handler
  73. func NewConnection(conn net.Conn, dbManager *storage.DatabaseManager, quiet bool) *Connection {
  74. return &Connection{
  75. conn: conn,
  76. reader: bufio.NewReader(conn),
  77. writer: bufio.NewWriter(conn),
  78. dbManager: dbManager,
  79. params: make(map[string]string),
  80. statements: make(map[string]*preparedStatement),
  81. portals: make(map[string]*portal),
  82. txStatus: TxStatusIdle,
  83. quiet: quiet,
  84. backendPID: nextBackendPID(),
  85. }
  86. }
  87. // Handle processes the connection
  88. func (c *Connection) Handle() error {
  89. defer func() {
  90. if c.executor != nil {
  91. if err := c.executor.Close(); err != nil && !c.quiet {
  92. log.Printf("failed to close session: %v", err)
  93. }
  94. }
  95. c.conn.Close()
  96. }()
  97. // First, check for SSL request (sent before startup message)
  98. // SSL request is 8 bytes: length(4) + code(4) where code = 80877103
  99. firstBytes := make([]byte, 8)
  100. n, err := io.ReadFull(c.reader, firstBytes)
  101. if err != nil {
  102. return fmt.Errorf("failed to read initial bytes: %w", err)
  103. }
  104. // Check if it's an SSL request (code 80877103 = 0x04D2162F)
  105. if n == 8 {
  106. length := binary.BigEndian.Uint32(firstBytes[0:4])
  107. code := binary.BigEndian.Uint32(firstBytes[4:8])
  108. if length == 8 && code == 80877103 {
  109. // SSL request - we don't support SSL, send 'N'
  110. if !c.quiet {
  111. log.Printf("Client requested SSL, sending rejection")
  112. }
  113. if _, err := c.conn.Write([]byte{'N'}); err != nil {
  114. return fmt.Errorf("failed to send SSL rejection: %w", err)
  115. }
  116. // Now read the actual startup message
  117. } else {
  118. // Not SSL request, this is part of startup message
  119. // We need to prepend these bytes back for ReadStartupMessage
  120. // Create a multi-reader that first reads our buffered bytes, then continues with the reader
  121. c.reader = bufio.NewReader(io.MultiReader(bytes.NewReader(firstBytes), c.reader))
  122. }
  123. }
  124. // Read startup message
  125. if !c.quiet {
  126. log.Printf("Reading startup message...")
  127. }
  128. params, err := ReadStartupMessage(c.reader)
  129. if err != nil {
  130. return fmt.Errorf("failed to read startup message: %w", err)
  131. }
  132. c.params = params
  133. if !c.quiet {
  134. log.Printf("Startup params: %+v", params)
  135. }
  136. // Get database name from params (default to "pizzasql")
  137. dbName := params["database"]
  138. if dbName == "" {
  139. dbName = "pizzasql"
  140. }
  141. c.database = dbName
  142. if !c.quiet {
  143. log.Printf("New connection: user=%s database=%s", params["user"], dbName)
  144. }
  145. // Initialize database
  146. if err := c.initDatabase(dbName); err != nil {
  147. c.sendError("FATAL", ErrCodeConnectionFailure, fmt.Sprintf("Failed to initialize database: %v", err))
  148. return err
  149. }
  150. // Send authentication OK (no auth for now)
  151. if err := c.sendAuthenticationOk(); err != nil {
  152. return err
  153. }
  154. // Send parameter status messages
  155. if err := c.sendParameterStatus("server_version", version.PostgreSQLCompatVersion+" (PizzaSQL)"); err != nil {
  156. return err
  157. }
  158. // Build identity is a separate, custom ParameterStatus so the PostgreSQL
  159. // compatibility string above stays stable for version-sniffing drivers.
  160. if err := c.sendParameterStatus("pizzasql.version", version.String()); err != nil {
  161. return err
  162. }
  163. if err := c.sendParameterStatus("pizzasql.commit", version.Commit); err != nil {
  164. return err
  165. }
  166. if err := c.sendParameterStatus("pizzasql.proxy_errors", "1"); err != nil {
  167. return err
  168. }
  169. if err := c.sendParameterStatus("server_encoding", "UTF8"); err != nil {
  170. return err
  171. }
  172. if err := c.sendParameterStatus("client_encoding", "UTF8"); err != nil {
  173. return err
  174. }
  175. if err := c.sendParameterStatus("DateStyle", "ISO, MDY"); err != nil {
  176. return err
  177. }
  178. if err := c.sendParameterStatus("TimeZone", "UTC"); err != nil {
  179. return err
  180. }
  181. // Send backend key data (for cancellation - we don't implement this yet)
  182. if err := c.sendBackendKeyData(c.backendPID, 67890); err != nil {
  183. return err
  184. }
  185. // Send ready for query
  186. if err := c.sendReadyForQuery(); err != nil {
  187. return err
  188. }
  189. // Read messages on a separate goroutine so an idle listener can receive
  190. // asynchronous NotificationResponse frames while blocked waiting for input.
  191. // Only this goroutine writes to c.writer, which keeps frame order intact.
  192. type readResult struct {
  193. msg *Message
  194. err error
  195. }
  196. inbox := make(chan readResult, 16)
  197. done := make(chan struct{})
  198. defer close(done)
  199. go func() {
  200. for {
  201. msg, err := ReadMessage(c.reader)
  202. select {
  203. case inbox <- readResult{msg: msg, err: err}:
  204. case <-done:
  205. return
  206. }
  207. if err != nil {
  208. return
  209. }
  210. }
  211. }()
  212. notifications := c.executor.NotificationChannel()
  213. overflow := c.executor.NotificationOverflow()
  214. for {
  215. // Do not interleave notifications into an extended-protocol cycle. The
  216. // channel is disabled until Sync closes the cycle.
  217. var notifyCh <-chan storage.Notification
  218. if !c.extendedCycle {
  219. notifyCh = notifications
  220. }
  221. select {
  222. case res := <-inbox:
  223. if res.err != nil {
  224. if res.err == io.EOF {
  225. log.Printf("Connection closed by client")
  226. return nil
  227. }
  228. return fmt.Errorf("failed to read message: %w", res.err)
  229. }
  230. switch res.msg.Type {
  231. case MsgParse, MsgBind, MsgDescribe, MsgExecute, MsgClose:
  232. c.extendedCycle = true
  233. }
  234. if err := c.handleMessage(res.msg); err != nil {
  235. if err == io.EOF {
  236. log.Printf("Connection closed normally")
  237. return nil
  238. }
  239. log.Printf("Error handling message: %v", err)
  240. return err
  241. }
  242. case n := <-notifyCh:
  243. if err := c.sendNotification(n); err != nil {
  244. return err
  245. }
  246. if err := c.writer.Flush(); err != nil {
  247. return err
  248. }
  249. case <-overflow:
  250. return fmt.Errorf("notification queue overflow: slow consumer disconnected")
  251. }
  252. }
  253. }
  254. // initDatabase initializes the database connection
  255. func (c *Connection) initDatabase(dbName string) error {
  256. db, err := c.dbManager.GetDatabase(dbName)
  257. if err != nil {
  258. return err
  259. }
  260. c.schema = db.Schema
  261. c.table = db.Table
  262. c.executor = executor.New(db.Schema, db.Table)
  263. c.executor.SetBackendPID(c.backendPID)
  264. c.executor.SetNotificationHub(db.Hub)
  265. c.executor.SyncCatalog()
  266. return nil
  267. }
  268. // handleMessage processes a client message
  269. func (c *Connection) handleMessage(msg *Message) error {
  270. if c.extendedFailed && msg.Type != MsgSync && msg.Type != MsgFlush && msg.Type != MsgTerminate {
  271. return nil
  272. }
  273. switch msg.Type {
  274. case MsgProxyError:
  275. return c.handleProxyError(msg)
  276. case MsgQuery:
  277. return c.handleQuery(msg)
  278. case MsgTerminate:
  279. log.Printf("Client requested termination")
  280. return io.EOF
  281. case MsgParse:
  282. return c.handleParse(msg)
  283. case MsgBind:
  284. return c.handleBind(msg)
  285. case MsgDescribe:
  286. return c.handleDescribe(msg)
  287. case MsgExecute:
  288. return c.handleExecute(msg)
  289. case MsgClose:
  290. return c.handleClose(msg)
  291. case MsgFlush:
  292. return c.writer.Flush()
  293. case MsgSync:
  294. c.extendedFailed = false
  295. c.extendedCycle = false
  296. if err := c.sendReadyForQuery(); err != nil {
  297. return err
  298. }
  299. return c.drainNotifications()
  300. default:
  301. log.Printf("Unknown message type: %c (%d)", msg.Type, msg.Type)
  302. c.sendError("ERROR", ErrCodeProtocolViolation, fmt.Sprintf("Unknown message type: %c", msg.Type))
  303. return c.sendReadyForQuery()
  304. }
  305. }
  306. // handleQuery processes a simple query
  307. func (c *Connection) handleQuery(msg *Message) error {
  308. // A Query message carries a single NUL-terminated query string.
  309. if len(msg.Data) == 0 || msg.Data[len(msg.Data)-1] != 0 {
  310. c.sendError("ERROR", ErrCodeProtocolViolation, "invalid Query message: missing null terminator")
  311. return c.sendReadyForQuery()
  312. }
  313. sql := string(msg.Data[:len(msg.Data)-1])
  314. if !c.quiet {
  315. log.Printf("Query: %s", sql)
  316. }
  317. // Handle empty query
  318. sqlTrimmed := strings.TrimSpace(sql)
  319. if sqlTrimmed == "" || sqlTrimmed == ";" {
  320. if err := c.sendEmptyQueryResponse(); err != nil {
  321. return err
  322. }
  323. return c.sendReadyForQuery()
  324. }
  325. // Handle special PostgreSQL system queries that drivers send
  326. singleStatement := isSingleStatementSQL(sql)
  327. // In a failed transaction only ROLLBACK (or ROLLBACK TO SAVEPOINT) is
  328. // accepted. Gate before honoring the special driver queries below so they
  329. // return 25P02 instead of a result. Multi-statement batches are gated
  330. // per statement in the execution loop below.
  331. if c.txStatus == TxStatusFailed && singleStatement && !isRollbackStatement(sql) {
  332. c.sendError("ERROR", ErrCodeTransactionAborted, "current transaction is aborted, commands ignored until end of transaction block")
  333. return c.sendReadyForQuery()
  334. }
  335. // Recognize only complete initialization-query token sequences.
  336. if singleStatement {
  337. switch kind := systemQueryKind(sql); kind {
  338. case "version":
  339. return c.handleVersionQuery()
  340. case "current_user":
  341. return c.handleCurrentUserQuery()
  342. case "server_version", "server_encoding", "client_encoding":
  343. return c.handleShowCommand(strings.ToUpper(kind))
  344. }
  345. }
  346. if result, handled, err := c.catalogResult(sql); handled {
  347. if err != nil {
  348. c.sendError("ERROR", ErrCodeInternalError, err.Error())
  349. return c.sendReadyForQuery()
  350. }
  351. if err := c.sendTabularResult(result, "SELECT"); err != nil {
  352. return err
  353. }
  354. return c.sendReadyForQuery()
  355. }
  356. // Parse the complete batch before executing its first statement. This keeps
  357. // unsupported trailing clauses from turning into committed writes.
  358. l := lexer.New(sql)
  359. p := parser.New(l)
  360. stmts, err := p.ParseMultiple()
  361. if err != nil {
  362. code := ErrCodeSyntaxError
  363. if errors.Is(err, pgerror.ErrFeatureNotSupported) {
  364. code = ErrCodeFeatureNotSupported
  365. }
  366. if c.txStatus == TxStatusInBlock {
  367. c.txStatus = TxStatusFailed
  368. }
  369. c.sendError("ERROR", code, fmt.Sprintf("Syntax error: %v", err))
  370. return c.sendReadyForQuery()
  371. }
  372. for _, stmt := range stmts {
  373. if c.txStatus == TxStatusFailed {
  374. if _, rollback := stmt.(*parser.RollbackStmt); !rollback {
  375. c.sendError("ERROR", ErrCodeTransactionAborted, "current transaction is aborted, commands ignored until end of transaction block")
  376. return c.sendReadyForQuery()
  377. }
  378. }
  379. result, err := c.executor.Execute(stmt)
  380. if err != nil && isIdleRollback(stmt, c.txStatus, err) {
  381. result, err = executor.NewResult("ROLLBACK"), nil
  382. }
  383. if err != nil {
  384. code := ErrCodeInternalError
  385. message := fmt.Sprintf("Execution error: %v", err)
  386. var primaryKeyErr *storage.PrimaryKeyViolationError
  387. var uniqueErr *storage.UniqueViolationError
  388. var notNullErr *storage.NotNullViolationError
  389. var checkErr *storage.CheckViolationError
  390. var foreignKeyErr *storage.ForeignKeyViolationError
  391. if errors.Is(err, storage.ErrSerialization) {
  392. code = ErrCodeSerializationFailure
  393. c.txStatus = TxStatusIdle
  394. } else if errors.Is(err, pgerror.ErrInvalidText) {
  395. code = ErrCodeInvalidText
  396. if c.txStatus == TxStatusInBlock {
  397. c.txStatus = TxStatusFailed
  398. }
  399. } else if errors.Is(err, pgerror.ErrInvalidParameter) {
  400. code = ErrCodeInvalidParameter
  401. if c.txStatus == TxStatusInBlock {
  402. c.txStatus = TxStatusFailed
  403. }
  404. } else if errors.Is(err, pgerror.ErrDatatypeMismatch) {
  405. code = ErrCodeDatatypeMismatch
  406. if c.txStatus == TxStatusInBlock {
  407. c.txStatus = TxStatusFailed
  408. }
  409. } else if analysisErr := analysisTypeMismatch(err); analysisErr {
  410. code = ErrCodeDatatypeMismatch
  411. if c.txStatus == TxStatusInBlock {
  412. c.txStatus = TxStatusFailed
  413. }
  414. } else if errors.As(err, &notNullErr) {
  415. code = "23502"
  416. if _, commit := stmt.(*parser.CommitStmt); commit {
  417. c.txStatus = TxStatusIdle
  418. } else if c.txStatus == TxStatusInBlock {
  419. c.txStatus = TxStatusFailed
  420. }
  421. } else if errors.As(err, &checkErr) {
  422. code = ErrCodeCheckViolation
  423. if _, commit := stmt.(*parser.CommitStmt); commit {
  424. c.txStatus = TxStatusIdle
  425. } else if c.txStatus == TxStatusInBlock {
  426. c.txStatus = TxStatusFailed
  427. }
  428. } else if errors.As(err, &foreignKeyErr) {
  429. code = ErrCodeForeignKeyViolation
  430. if _, commit := stmt.(*parser.CommitStmt); commit {
  431. c.txStatus = TxStatusIdle
  432. } else if c.txStatus == TxStatusInBlock {
  433. c.txStatus = TxStatusFailed
  434. }
  435. } else if errors.As(err, &uniqueErr) || errors.As(err, &primaryKeyErr) {
  436. code = ErrCodeUniqueViolation
  437. if uniqueErr != nil {
  438. message = fmt.Sprintf("Execution error: UNIQUE constraint failed: %s", uniqueErr.Constraint)
  439. }
  440. if _, commit := stmt.(*parser.CommitStmt); commit {
  441. c.txStatus = TxStatusIdle
  442. } else if c.txStatus == TxStatusInBlock {
  443. c.txStatus = TxStatusFailed
  444. }
  445. } else if errors.Is(err, pgerror.ErrFeatureNotSupported) || errors.Is(err, executor.ErrUnsupportedFeature) {
  446. code = ErrCodeFeatureNotSupported
  447. if c.txStatus == TxStatusInBlock {
  448. c.txStatus = TxStatusFailed
  449. }
  450. } else if _, commit := stmt.(*parser.CommitStmt); commit {
  451. // A failed COMMIT has already rolled the transaction back in
  452. // storage; leaving the session in the failed state would make
  453. // every following statement (including ROLLBACK) fail.
  454. c.txStatus = TxStatusIdle
  455. } else if c.txStatus == TxStatusInBlock {
  456. c.txStatus = TxStatusFailed
  457. }
  458. c.sendError("ERROR", code, message)
  459. return c.sendReadyForQuery()
  460. }
  461. if err := c.sendResult(result, stmt); err != nil {
  462. return err
  463. }
  464. if result.LSN > 0 {
  465. if err := c.sendLSN(result.LSN); err != nil {
  466. return err
  467. }
  468. }
  469. }
  470. return c.sendReadyForQuery()
  471. }
  472. func (c *Connection) handleParse(msg *Message) error {
  473. if c.extendedFailed {
  474. return nil
  475. }
  476. name, pos, err := readCString(msg.Data, 0)
  477. if err != nil {
  478. return c.failExtended(ErrCodeProtocolViolation, err)
  479. }
  480. query, pos, err := readCString(msg.Data, pos)
  481. if err != nil || pos+2 > len(msg.Data) {
  482. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Parse message"))
  483. }
  484. count := int(binary.BigEndian.Uint16(msg.Data[pos : pos+2]))
  485. pos += 2
  486. if pos+count*4 != len(msg.Data) {
  487. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Parse parameter list"))
  488. }
  489. oids := make([]int32, count)
  490. for i := range oids {
  491. oids[i] = int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  492. pos += 4
  493. }
  494. if !isSingleStatementSQL(query) {
  495. return c.failExtended(ErrCodeSyntaxError, fmt.Errorf("prepared statements must contain one command"))
  496. }
  497. c.statements[name] = &preparedStatement{query: query, paramOIDs: c.negotiateParameterOIDs(query, oids)}
  498. return c.writeMessage(MsgParseComplete, nil)
  499. }
  500. func (c *Connection) handleBind(msg *Message) error {
  501. if c.extendedFailed {
  502. return nil
  503. }
  504. portalName, pos, err := readCString(msg.Data, 0)
  505. if err != nil {
  506. return c.failExtended(ErrCodeProtocolViolation, err)
  507. }
  508. statementName, pos, err := readCString(msg.Data, pos)
  509. if err != nil {
  510. return c.failExtended(ErrCodeProtocolViolation, err)
  511. }
  512. statement, ok := c.statements[statementName]
  513. if !ok {
  514. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("prepared statement %q does not exist", statementName))
  515. }
  516. formats, pos, err := readInt16List(msg.Data, pos)
  517. if err != nil || pos+2 > len(msg.Data) {
  518. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind format list"))
  519. }
  520. paramCount := int(binary.BigEndian.Uint16(msg.Data[pos : pos+2]))
  521. pos += 2
  522. if len(formats) > 1 && len(formats) != paramCount {
  523. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("Bind parameter format count does not match parameters"))
  524. }
  525. for _, format := range formats {
  526. if format != 0 && format != 1 {
  527. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter format code"))
  528. }
  529. }
  530. params := make([]boundParameter, paramCount)
  531. for i := range params {
  532. if pos+4 > len(msg.Data) {
  533. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter"))
  534. }
  535. length := int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  536. pos += 4
  537. params[i].oid = parameterOID(statement.paramOIDs, i)
  538. params[i].format = parameterFormat(formats, i)
  539. if length == -1 {
  540. params[i].null = true
  541. continue
  542. }
  543. if length < 0 || pos+int(length) > len(msg.Data) {
  544. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter length"))
  545. }
  546. params[i].value = append([]byte(nil), msg.Data[pos:pos+int(length)]...)
  547. pos += int(length)
  548. }
  549. resultFormats, pos, err := readInt16List(msg.Data, pos)
  550. if err != nil || pos != len(msg.Data) {
  551. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind result format list"))
  552. }
  553. for _, format := range resultFormats {
  554. if format != 0 && format != 1 {
  555. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind result format code"))
  556. }
  557. if format == 1 {
  558. return c.failExtended(ErrCodeFeatureNotSupported, fmt.Errorf("binary result format is not supported; request text results"))
  559. }
  560. }
  561. if len(resultFormats) > 1 {
  562. return c.failExtended(ErrCodeFeatureNotSupported, fmt.Errorf("per-column result format lists are not supported; request all-text results"))
  563. }
  564. query, err := bindQuery(statement.query, params)
  565. if err != nil {
  566. code := ErrCodeInvalidParameter
  567. if errors.Is(err, pgerror.ErrFeatureNotSupported) {
  568. code = ErrCodeFeatureNotSupported
  569. }
  570. if errors.Is(err, pgerror.ErrInvalidText) {
  571. code = ErrCodeInvalidText
  572. }
  573. if errors.Is(err, pgerror.ErrInvalidParameter) {
  574. code = ErrCodeInvalidParameter
  575. }
  576. return c.failExtended(code, err)
  577. }
  578. c.portals[portalName] = &portal{query: query, paramOIDs: append([]int32(nil), statement.paramOIDs...)}
  579. return c.writeMessage(MsgBindComplete, nil)
  580. }
  581. func (c *Connection) handleDescribe(msg *Message) error {
  582. if c.extendedFailed {
  583. return nil
  584. }
  585. if len(msg.Data) < 2 {
  586. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe message"))
  587. }
  588. name, pos, err := readCString(msg.Data, 1)
  589. if err != nil || pos != len(msg.Data) {
  590. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe name"))
  591. }
  592. switch msg.Data[0] {
  593. case 'S':
  594. statement, ok := c.statements[name]
  595. if !ok {
  596. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("prepared statement %q does not exist", name))
  597. }
  598. if err := c.sendParameterDescription(statement.paramOIDs); err != nil {
  599. return err
  600. }
  601. case 'P':
  602. portal, ok := c.portals[name]
  603. if !ok {
  604. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("portal %q does not exist", name))
  605. }
  606. if err := c.sendParameterDescription(portal.paramOIDs); err != nil {
  607. return err
  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 {
  1097. return "", fmt.Errorf("invalid binary boolean")
  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 or a bound portal.
  1337. func (c *Connection) sendParameterDescription(oids []int32) error {
  1338. mb := NewMessageBuilder()
  1339. mb.WriteInt16(int16(len(oids)))
  1340. for _, oid := range oids {
  1341. mb.WriteInt32(oid)
  1342. }
  1343. return c.writeMessage(MsgParameterDescription, mb.Bytes())
  1344. }
  1345. // sendRowDescription sends row description (column metadata)
  1346. func (c *Connection) sendRowDescription(columns []string, columnTypes []string) error {
  1347. mb := NewMessageBuilder()
  1348. mb.WriteInt16(int16(len(columns)))
  1349. for i, col := range columns {
  1350. colType := ""
  1351. if i < len(columnTypes) {
  1352. colType = columnTypes[i]
  1353. }
  1354. mb.WriteString(col)
  1355. mb.WriteInt32(0) // table OID
  1356. mb.WriteInt16(0) // column attribute number
  1357. mb.WriteInt32(c.getOIDForType(colType)) // type OID
  1358. mb.WriteInt16(c.getTypeSizeForType(colType)) // type size
  1359. mb.WriteInt32(-1) // type modifier
  1360. mb.WriteInt16(0) // format code (text)
  1361. }
  1362. return c.writeMessage(MsgRowDescription, mb.Bytes())
  1363. }
  1364. // sendDataRow sends a data row
  1365. func (c *Connection) sendDataRow(row []interface{}, columns []string) error {
  1366. mb := NewMessageBuilder()
  1367. mb.WriteInt16(int16(len(row)))
  1368. for _, value := range row {
  1369. if value == nil {
  1370. mb.WriteInt32(-1) // NULL indicator
  1371. continue
  1372. }
  1373. // Convert value to string
  1374. strValue := c.valueToString(value)
  1375. mb.WriteInt32(int32(len(strValue)))
  1376. mb.WriteBytes([]byte(strValue))
  1377. }
  1378. return c.writeMessage(MsgDataRow, mb.Bytes())
  1379. }
  1380. // sendCommandComplete sends command complete message
  1381. func (c *Connection) sendCommandComplete(tag string) error {
  1382. mb := NewMessageBuilder()
  1383. mb.WriteString(tag)
  1384. return c.writeMessage(MsgCommandComplete, mb.Bytes())
  1385. }
  1386. // sendError sends an error response
  1387. func (c *Connection) sendError(severity, code, message string) error {
  1388. if severity == "ERROR" && c.txStatus == TxStatusInBlock {
  1389. c.txStatus = TxStatusFailed
  1390. }
  1391. mb := NewMessageBuilder()
  1392. mb.AppendByte(ErrorFieldSeverity)
  1393. mb.WriteString(severity)
  1394. mb.AppendByte(ErrorFieldCode)
  1395. mb.WriteString(code)
  1396. mb.AppendByte(ErrorFieldMessage)
  1397. mb.WriteString(message)
  1398. mb.AppendByte(0) // Terminator
  1399. if err := c.writeMessage(MsgErrorResponse, mb.Bytes()); err != nil {
  1400. return err
  1401. }
  1402. // Errors must be visible promptly, including FATAL startup failures that
  1403. // are not followed by a ReadyForQuery before the connection closes.
  1404. return c.writer.Flush()
  1405. }
  1406. // writeMessage buffers a message for the connection. It does not flush, so
  1407. // callers that need to make a response visible to the client must flush at the
  1408. // appropriate protocol boundary (ReadyForQuery, an explicit Flush message, or
  1409. // an error response). Buffering amortizes the per-message syscalls that a
  1410. // result set would otherwise incur; the underlying bufio.Writer bounds memory
  1411. // use so large result sets cannot grow the buffer without limit.
  1412. func (c *Connection) writeMessage(msgType byte, data []byte) error {
  1413. if !c.quiet {
  1414. log.Printf("Sending message type=%c length=%d", msgType, len(data)+4)
  1415. }
  1416. return WriteMessage(c.writer, msgType, data)
  1417. }
  1418. // arrayElementTypeName reports the element type of an array type name such as
  1419. // "INTEGER[]". It reports false for scalar type names.
  1420. func arrayElementTypeName(typeName string) (string, bool) {
  1421. upper := strings.ToUpper(strings.TrimSpace(typeName))
  1422. if !strings.HasSuffix(upper, "[]") {
  1423. return "", false
  1424. }
  1425. return strings.TrimSpace(strings.TrimSuffix(upper, "[]")), true
  1426. }
  1427. // arrayOIDForElement maps an array element type name to its PostgreSQL array
  1428. // OID. Narrower integer types report int8[] because values are not
  1429. // range-checked, matching the scalar carrier rule; NUMERIC reports numeric[]
  1430. // because array elements stay text.
  1431. func arrayOIDForElement(element string) int32 {
  1432. base := strings.ToUpper(strings.TrimSpace(element))
  1433. if idx := strings.IndexByte(base, '('); idx >= 0 {
  1434. base = strings.TrimSpace(base[:idx])
  1435. }
  1436. switch base {
  1437. case "INTEGER", "INT", "INT4":
  1438. return 1007 // INT4ARRAYOID
  1439. case "BIGINT", "INT8", "SMALLINT", "INT2", "TINYINT", "MEDIUMINT":
  1440. return 1016 // INT8ARRAYOID
  1441. case "BOOLEAN", "BOOL":
  1442. return 1000 // BOOLARRAYOID
  1443. case "REAL", "FLOAT", "FLOAT4":
  1444. return 1021 // FLOAT4ARRAYOID
  1445. case "DOUBLE", "DOUBLE PRECISION", "FLOAT8":
  1446. return 1022 // FLOAT8ARRAYOID
  1447. case "NUMERIC", "DECIMAL":
  1448. return 1231 // NUMERICARRAYOID
  1449. case "VARCHAR", "NVARCHAR", "CHARACTER VARYING":
  1450. return 1015 // VARCHARARRAYOID
  1451. default:
  1452. return 1009 // TEXTARRAYOID
  1453. }
  1454. }
  1455. // arrayParamElementType maps an array parameter OID to the element type the
  1456. // bound literal is cast to. Unknown OIDs are handled by callers.
  1457. func arrayParamElementType(oid int32) (string, bool) {
  1458. switch oid {
  1459. case 1009:
  1460. return "TEXT", true
  1461. case 1015:
  1462. return "VARCHAR", true
  1463. case 1007:
  1464. return "INTEGER", true
  1465. case 1016:
  1466. return "BIGINT", true
  1467. case 1005:
  1468. return "SMALLINT", true
  1469. case 1000:
  1470. return "BOOLEAN", true
  1471. case 1021:
  1472. return "REAL", true
  1473. case 1022:
  1474. return "DOUBLE", true
  1475. case 1231:
  1476. return "NUMERIC", true
  1477. default:
  1478. return "", false
  1479. }
  1480. }
  1481. // getOIDForType returns PostgreSQL OID for type.
  1482. //
  1483. // Types narrower than the value the engine carries are reported as the carrier
  1484. // type, because the engine does not range-check stored or cast values: a value
  1485. // that does not fit int2/int4 or float4 would fail client-side decoding rather
  1486. // than having been rejected on write. INTEGER and REAL keep their declared
  1487. // mappings, which predate this rule and are what existing clients expect.
  1488. func (c *Connection) getOIDForType(typeName string) int32 {
  1489. if element, ok := arrayElementTypeName(typeName); ok {
  1490. return arrayOIDForElement(element)
  1491. }
  1492. switch strings.ToUpper(typeName) {
  1493. case "SMALLINT", "INT2", "TINYINT", "MEDIUMINT":
  1494. // Carried as int64 and not range-checked, so int8 is the honest type.
  1495. return 20 // INT8OID
  1496. case "INTEGER", "INT", "INT4":
  1497. return 23 // INT4OID
  1498. case "BIGINT", "INT8":
  1499. return 20 // INT8OID
  1500. case "NUMERIC", "DECIMAL":
  1501. // Values round-trip through JSON as float64; there is no exact decimal
  1502. // carrier, so NUMERIC is not advertised.
  1503. return 701 // FLOAT8OID
  1504. case "JSONB":
  1505. return 3802 // JSONBOID
  1506. case "TEXT", "VARCHAR", "CHAR", "UUID":
  1507. // UUID is stored as text (SQLite-style), so it reports TEXTOID rather
  1508. // than the native PG UUID OID.
  1509. return 25 // TEXTOID
  1510. case "REAL", "FLOAT":
  1511. return 700 // FLOAT4OID
  1512. case "DOUBLE":
  1513. return 701 // FLOAT8OID
  1514. case "BOOLEAN", "BOOL":
  1515. return 16 // BOOLOID
  1516. case "BLOB":
  1517. return 17 // BYTEAOID
  1518. case "DATETIME", "TIMESTAMP":
  1519. // Datetime values are exchanged as UTC RFC3339 (ISO8601 with a timezone
  1520. // offset), which timestamptz decodes directly.
  1521. return 1184 // TIMESTAMPTZOID
  1522. case "DATE":
  1523. return 1082 // DATEOID
  1524. default:
  1525. return 25 // Default to TEXT
  1526. }
  1527. }
  1528. // getTypeSizeForType returns type size in bytes, or -1 for variable length.
  1529. func (c *Connection) getTypeSizeForType(typeName string) int16 {
  1530. if _, ok := arrayElementTypeName(typeName); ok {
  1531. return -1 // arrays are variable length
  1532. }
  1533. switch strings.ToUpper(typeName) {
  1534. case "SMALLINT", "INT2", "TINYINT", "MEDIUMINT":
  1535. return 8 // Reported as int8; see getOIDForType.
  1536. case "INTEGER", "INT", "INT4":
  1537. return 4
  1538. case "BIGINT", "INT8":
  1539. return 8
  1540. case "NUMERIC", "DECIMAL":
  1541. return 8 // Reported as float8; see getOIDForType.
  1542. case "REAL", "FLOAT":
  1543. return 4
  1544. case "DOUBLE":
  1545. return 8
  1546. case "BOOLEAN", "BOOL":
  1547. return 1
  1548. case "DATETIME", "TIMESTAMP":
  1549. return 8
  1550. case "DATE":
  1551. return 4
  1552. default:
  1553. return -1 // Variable length
  1554. }
  1555. }
  1556. // valueToString converts a value to string
  1557. func (c *Connection) valueToString(value interface{}) string {
  1558. if value == nil {
  1559. return ""
  1560. }
  1561. // PostgreSQL's text format for bytea is \x followed by hex. Emitting that
  1562. // lets libpq/pgx decode a BLOB column (OID 17) losslessly.
  1563. if b, ok := value.([]byte); ok {
  1564. return `\x` + hex.EncodeToString(b)
  1565. }
  1566. return fmt.Sprintf("%v", value)
  1567. }
  1568. // handleVersionQuery handles SELECT version()
  1569. func (c *Connection) handleVersionQuery() error {
  1570. columns := []string{"version"}
  1571. columnTypes := []string{"TEXT"}
  1572. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1573. return err
  1574. }
  1575. row := []interface{}{"PostgreSQL " + version.PostgreSQLCompatVersion + " (PizzaSQL)"}
  1576. if err := c.sendDataRow(row, columns); err != nil {
  1577. return err
  1578. }
  1579. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1580. return err
  1581. }
  1582. return c.sendReadyForQuery()
  1583. }
  1584. // handleCurrentUserQuery handles SELECT current_user
  1585. func (c *Connection) handleCurrentUserQuery() error {
  1586. columns := []string{"current_user"}
  1587. columnTypes := []string{"TEXT"}
  1588. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1589. return err
  1590. }
  1591. user := c.params["user"]
  1592. if user == "" {
  1593. user = "pizzasql"
  1594. }
  1595. row := []interface{}{user}
  1596. if err := c.sendDataRow(row, columns); err != nil {
  1597. return err
  1598. }
  1599. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1600. return err
  1601. }
  1602. return c.sendReadyForQuery()
  1603. }
  1604. // handleShowCommand handles SHOW commands
  1605. func (c *Connection) handleShowCommand(sqlUpper string) error {
  1606. var value string
  1607. var name string
  1608. if sqlUpper == "SERVER_VERSION" {
  1609. name = "server_version"
  1610. value = version.PostgreSQLCompatVersion
  1611. } else if sqlUpper == "SERVER_ENCODING" {
  1612. name = "server_encoding"
  1613. value = "UTF8"
  1614. } else if sqlUpper == "CLIENT_ENCODING" {
  1615. name = "client_encoding"
  1616. value = "UTF8"
  1617. } else {
  1618. // Unknown SHOW command
  1619. c.sendError("ERROR", ErrCodeFeatureNotSupported, "SHOW command not supported")
  1620. return c.sendReadyForQuery()
  1621. }
  1622. columns := []string{name}
  1623. columnTypes := []string{"TEXT"}
  1624. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1625. return err
  1626. }
  1627. row := []interface{}{value}
  1628. if err := c.sendDataRow(row, columns); err != nil {
  1629. return err
  1630. }
  1631. if err := c.sendCommandComplete("SHOW"); err != nil {
  1632. return err
  1633. }
  1634. return c.sendReadyForQuery()
  1635. }