connection.go 45 KB

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