connection.go 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  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. if _, ok := c.statements[name]; !ok {
  536. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("prepared statement %q does not exist", name))
  537. }
  538. case 'P':
  539. if _, ok := c.portals[name]; !ok {
  540. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("portal %q does not exist", name))
  541. }
  542. default:
  543. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe target"))
  544. }
  545. // Do not claim NoData for row-producing statements or execute queries to
  546. // discover metadata. Clients must avoid Describe until side-effect-free
  547. // parameter/row description is implemented.
  548. return c.failExtended(ErrCodeFeatureNotSupported, fmt.Errorf("Describe metadata is not supported; use simple query or Parse/Bind/Execute without Describe"))
  549. }
  550. func (c *Connection) handleExecute(msg *Message) error {
  551. if c.extendedFailed {
  552. return nil
  553. }
  554. name, pos, err := readCString(msg.Data, 0)
  555. if err != nil || pos+4 != len(msg.Data) {
  556. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Execute message"))
  557. }
  558. portal, ok := c.portals[name]
  559. if !ok {
  560. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("portal %q does not exist", name))
  561. }
  562. if portal.executed {
  563. return c.failExtended(ErrCodeFeatureNotSupported, fmt.Errorf("portal can only be executed once"))
  564. }
  565. maxRows := int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  566. if maxRows < 0 {
  567. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Execute row limit"))
  568. }
  569. // Check the transaction state before catalog emulation. Catalog queries do
  570. // not all parse as regular PizzaSQL statements, but must still return 25P02
  571. // while the transaction is aborted.
  572. if c.txStatus == TxStatusFailed && !isRollbackStatement(portal.query) {
  573. return c.failExtended(ErrCodeTransactionAborted, fmt.Errorf("current transaction is aborted, commands ignored until end of transaction block"))
  574. }
  575. if maxRows != 0 {
  576. return c.failExtended(ErrCodeFeatureNotSupported, fmt.Errorf("bounded Execute is not supported; use maxRows=0"))
  577. }
  578. portal.executed = true
  579. if result, handled, catalogErr := c.catalogResult(portal.query); handled {
  580. if catalogErr != nil {
  581. return c.failExtended(ErrCodeInternalError, catalogErr)
  582. }
  583. return c.sendTabularResult(result, "SELECT")
  584. }
  585. l := lexer.New(portal.query)
  586. stmt, err := parser.New(l).Parse()
  587. if err != nil {
  588. code := ErrCodeSyntaxError
  589. if errors.Is(err, pgerror.ErrFeatureNotSupported) {
  590. code = ErrCodeFeatureNotSupported
  591. if c.txStatus == TxStatusInBlock {
  592. c.txStatus = TxStatusFailed
  593. }
  594. }
  595. return c.failExtended(code, fmt.Errorf("syntax error: %w", err))
  596. }
  597. result, err := c.executor.Execute(stmt)
  598. if err != nil {
  599. code := ErrCodeInternalError
  600. var primaryKeyErr *storage.PrimaryKeyViolationError
  601. var uniqueErr *storage.UniqueViolationError
  602. var notNullErr *storage.NotNullViolationError
  603. if errors.Is(err, storage.ErrSerialization) {
  604. code = ErrCodeSerializationFailure
  605. c.txStatus = TxStatusIdle
  606. } else if errors.As(err, &notNullErr) {
  607. code = "23502"
  608. if c.txStatus == TxStatusInBlock {
  609. c.txStatus = TxStatusFailed
  610. }
  611. } else if errors.As(err, &uniqueErr) || errors.As(err, &primaryKeyErr) {
  612. code = ErrCodeUniqueViolation
  613. if _, commit := stmt.(*parser.CommitStmt); commit {
  614. c.txStatus = TxStatusIdle
  615. } else if c.txStatus == TxStatusInBlock {
  616. c.txStatus = TxStatusFailed
  617. }
  618. } else if errors.Is(err, pgerror.ErrFeatureNotSupported) || errors.Is(err, executor.ErrUnsupportedFeature) {
  619. code = ErrCodeFeatureNotSupported
  620. if c.txStatus == TxStatusInBlock {
  621. c.txStatus = TxStatusFailed
  622. }
  623. } else if _, commit := stmt.(*parser.CommitStmt); commit {
  624. c.txStatus = TxStatusIdle
  625. } else if c.txStatus == TxStatusInBlock {
  626. c.txStatus = TxStatusFailed
  627. }
  628. if uniqueErr != nil {
  629. return c.failExtended(code, fmt.Errorf("execution error: UNIQUE constraint failed: %s", uniqueErr.Constraint))
  630. }
  631. return c.failExtended(code, fmt.Errorf("execution error: %w", err))
  632. }
  633. if err := c.sendResult(result, stmt); err != nil {
  634. return err
  635. }
  636. if result.LSN > 0 {
  637. return c.sendLSN(result.LSN)
  638. }
  639. return nil
  640. }
  641. var catalogFilterPattern = regexp.MustCompile(`(?i)\b(table_name|tablename|table_schema|schemaname|constraint_name|indexname)\s*=\s*'((?:''|[^'])*)'`)
  642. func (c *Connection) catalogResult(sql string) (*executor.Result, bool, error) {
  643. if !isSingleStatementSQL(sql) {
  644. return nil, false, nil
  645. }
  646. source := catalogSource(sql)
  647. if source == "" {
  648. return nil, false, nil
  649. }
  650. if c.txStatus == TxStatusIdle {
  651. c.schema.LockStatement()
  652. defer c.schema.UnlockStatement()
  653. }
  654. tables, err := c.schema.ListTables()
  655. if err != nil {
  656. return nil, true, err
  657. }
  658. rows := make([]map[string]interface{}, 0)
  659. switch source {
  660. case "INFORMATION_SCHEMA.TABLES":
  661. for _, table := range tables {
  662. rows = append(rows, map[string]interface{}{
  663. "table_catalog": c.database, "table_schema": "public", "table_name": table, "table_type": "BASE TABLE",
  664. })
  665. }
  666. case "PG_TABLES":
  667. for _, table := range tables {
  668. indexes, _ := c.schema.ListTableIndexes(table)
  669. rows = append(rows, map[string]interface{}{
  670. "schemaname": "public", "tablename": table, "tableowner": c.params["user"], "tablespace": nil,
  671. "hasindexes": len(indexes) > 0, "hasrules": false, "hastriggers": false, "rowsecurity": false,
  672. })
  673. }
  674. case "INFORMATION_SCHEMA.COLUMNS":
  675. for _, table := range tables {
  676. schema, schemaErr := c.schema.GetSchema(table)
  677. if schemaErr != nil {
  678. continue
  679. }
  680. for i, column := range schema.Columns {
  681. rows = append(rows, map[string]interface{}{
  682. "table_catalog": c.database, "table_schema": "public", "table_name": table,
  683. "column_name": column.Name, "ordinal_position": int64(i + 1), "column_default": column.Default,
  684. "is_nullable": yesNo(column.Nullable), "data_type": strings.ToLower(column.Type),
  685. })
  686. }
  687. }
  688. case "INFORMATION_SCHEMA.TABLE_CONSTRAINTS", "INFORMATION_SCHEMA.KEY_COLUMN_USAGE":
  689. for _, table := range tables {
  690. schema, schemaErr := c.schema.GetSchema(table)
  691. if schemaErr != nil || schema.PrimaryKey == "" || schema.PrimaryKey == "_rowid_" {
  692. continue
  693. }
  694. row := map[string]interface{}{
  695. "constraint_catalog": c.database, "constraint_schema": "public", "constraint_name": table + "_pkey",
  696. "table_catalog": c.database, "table_schema": "public", "table_name": table,
  697. }
  698. if source == "INFORMATION_SCHEMA.TABLE_CONSTRAINTS" {
  699. row["constraint_type"] = "PRIMARY KEY"
  700. row["is_deferrable"] = "NO"
  701. row["initially_deferred"] = "NO"
  702. } else {
  703. row["column_name"] = schema.PrimaryKey
  704. row["ordinal_position"] = int64(1)
  705. }
  706. rows = append(rows, row)
  707. }
  708. case "PG_INDEXES":
  709. for _, table := range tables {
  710. indexes, _ := c.schema.ListTableIndexes(table)
  711. for _, index := range indexes {
  712. columns := make([]string, len(index.Columns))
  713. for i, column := range index.Columns {
  714. columns[i] = column.Name
  715. }
  716. unique := ""
  717. if index.Unique {
  718. unique = "UNIQUE "
  719. }
  720. rows = append(rows, map[string]interface{}{
  721. "schemaname": "public", "tablename": table, "indexname": index.Name, "tablespace": nil,
  722. "indexdef": fmt.Sprintf("CREATE %sINDEX %s ON %s (%s)", unique, index.Name, table, strings.Join(columns, ", ")),
  723. })
  724. }
  725. }
  726. }
  727. for _, match := range catalogFilterPattern.FindAllStringSubmatch(sql, -1) {
  728. column, expected := strings.ToLower(match[1]), strings.ReplaceAll(match[2], "''", "'")
  729. filtered := rows[:0]
  730. for _, row := range rows {
  731. if value, ok := row[column]; ok && strings.EqualFold(fmt.Sprintf("%v", value), expected) {
  732. filtered = append(filtered, row)
  733. }
  734. }
  735. rows = filtered
  736. }
  737. columns := catalogProjection(sql, rows)
  738. result := executor.NewResult("SELECT")
  739. if len(columns) == 1 && columns[0] == "count(*)" {
  740. result.AddColumnWithType("count", "INTEGER")
  741. result.AddRow(int64(len(rows)))
  742. return result, true, nil
  743. }
  744. for _, column := range columns {
  745. columnType := "TEXT"
  746. if column == "ordinal_position" {
  747. columnType = "INTEGER"
  748. } else if strings.HasPrefix(column, "has") || column == "rowsecurity" {
  749. columnType = "BOOLEAN"
  750. }
  751. result.AddColumnWithType(column, columnType)
  752. }
  753. for _, row := range rows {
  754. values := make([]interface{}, len(columns))
  755. for i, column := range columns {
  756. values[i] = row[column]
  757. }
  758. result.AddRow(values...)
  759. }
  760. return result, true, nil
  761. }
  762. // isRollbackStatement reports whether sql parses as a single ROLLBACK
  763. // statement, including ROLLBACK TO SAVEPOINT.
  764. func isRollbackStatement(sql string) bool {
  765. stmt, err := parser.New(lexer.New(sql)).Parse()
  766. if err != nil {
  767. return false
  768. }
  769. _, ok := stmt.(*parser.RollbackStmt)
  770. return ok
  771. }
  772. func catalogProjection(sql string, rows []map[string]interface{}) []string {
  773. upper := strings.ToUpper(sql)
  774. selectPos, fromPos := strings.Index(upper, "SELECT"), strings.Index(upper, " FROM ")
  775. if selectPos < 0 || fromPos < 0 || fromPos <= selectPos+6 {
  776. return nil
  777. }
  778. projection := strings.TrimSpace(sql[selectPos+6 : fromPos])
  779. projection = strings.TrimSpace(strings.TrimPrefix(strings.ToUpper(projection), "DISTINCT "))
  780. if projection == "*" && len(rows) > 0 {
  781. columns := make([]string, 0, len(rows[0]))
  782. for column := range rows[0] {
  783. columns = append(columns, column)
  784. }
  785. sort.Strings(columns)
  786. return columns
  787. }
  788. parts := strings.Split(projection, ",")
  789. columns := make([]string, 0, len(parts))
  790. for _, part := range parts {
  791. column := strings.TrimSpace(part)
  792. if index := strings.Index(strings.ToUpper(column), " AS "); index >= 0 {
  793. column = strings.TrimSpace(column[:index])
  794. }
  795. if index := strings.LastIndex(column, "."); index >= 0 {
  796. column = column[index+1:]
  797. }
  798. columns = append(columns, strings.ToLower(strings.Trim(column, `"`)))
  799. }
  800. return columns
  801. }
  802. func yesNo(value bool) string {
  803. if value {
  804. return "YES"
  805. }
  806. return "NO"
  807. }
  808. func (c *Connection) sendTabularResult(result *executor.Result, tag string) error {
  809. if err := c.sendRowDescription(result.Columns, result.ColumnTypes); err != nil {
  810. return err
  811. }
  812. for _, row := range result.Rows {
  813. if err := c.sendDataRow(row, result.Columns); err != nil {
  814. return err
  815. }
  816. }
  817. return c.sendCommandComplete(fmt.Sprintf("%s %d", tag, len(result.Rows)))
  818. }
  819. func (c *Connection) handleClose(msg *Message) error {
  820. if c.extendedFailed {
  821. return nil
  822. }
  823. if len(msg.Data) < 2 {
  824. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close message"))
  825. }
  826. name, pos, err := readCString(msg.Data, 1)
  827. if err != nil || pos != len(msg.Data) {
  828. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close name"))
  829. }
  830. if msg.Data[0] == 'S' {
  831. delete(c.statements, name)
  832. } else if msg.Data[0] == 'P' {
  833. delete(c.portals, name)
  834. } else {
  835. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close target"))
  836. }
  837. return c.writeMessage(MsgCloseComplete, nil)
  838. }
  839. func (c *Connection) failExtended(code string, err error) error {
  840. c.extendedFailed = true
  841. if c.txStatus == TxStatusInBlock {
  842. c.txStatus = TxStatusFailed
  843. }
  844. return c.sendError("ERROR", code, err.Error())
  845. }
  846. func (c *Connection) handleProxyError(msg *Message) error {
  847. if len(msg.Data) != 1 || (msg.Data[0] != MsgQuery && msg.Data[0] != MsgParse) {
  848. _ = c.sendError("FATAL", ErrCodeProtocolViolation, "invalid proxy error relay")
  849. return io.EOF
  850. }
  851. code, message := "42501", "permission denied by API key scopes"
  852. if c.txStatus == TxStatusFailed {
  853. code, message = ErrCodeTransactionAborted, "current transaction is aborted, commands ignored until end of transaction block"
  854. }
  855. if msg.Data[0] == MsgParse {
  856. c.extendedCycle = true
  857. return c.failExtended(code, errors.New(message))
  858. }
  859. if c.txStatus == TxStatusInBlock {
  860. c.txStatus = TxStatusFailed
  861. }
  862. if err := c.sendError("ERROR", code, message); err != nil {
  863. return err
  864. }
  865. return c.sendReadyForQuery()
  866. }
  867. type boundParameter struct {
  868. value []byte
  869. oid int32
  870. format int16
  871. null bool
  872. }
  873. func readCString(data []byte, pos int) (string, int, error) {
  874. if pos < 0 || pos >= len(data) {
  875. return "", pos, fmt.Errorf("missing null-terminated string")
  876. }
  877. end := bytes.IndexByte(data[pos:], 0)
  878. if end < 0 {
  879. return "", pos, fmt.Errorf("unterminated string")
  880. }
  881. return string(data[pos : pos+end]), pos + end + 1, nil
  882. }
  883. func readInt16List(data []byte, pos int) ([]int16, int, error) {
  884. if pos+2 > len(data) {
  885. return nil, pos, fmt.Errorf("missing list length")
  886. }
  887. count := int(binary.BigEndian.Uint16(data[pos : pos+2]))
  888. pos += 2
  889. if pos+count*2 > len(data) {
  890. return nil, pos, fmt.Errorf("truncated list")
  891. }
  892. result := make([]int16, count)
  893. for i := range result {
  894. result[i] = int16(binary.BigEndian.Uint16(data[pos : pos+2]))
  895. pos += 2
  896. }
  897. return result, pos, nil
  898. }
  899. func parameterOID(oids []int32, index int) int32 {
  900. if index < len(oids) {
  901. return oids[index]
  902. }
  903. return 0
  904. }
  905. func parameterFormat(formats []int16, index int) int16 {
  906. if len(formats) == 1 {
  907. return formats[0]
  908. }
  909. if index < len(formats) {
  910. return formats[index]
  911. }
  912. return 0
  913. }
  914. func bindQuery(query string, params []boundParameter) (string, error) {
  915. var result strings.Builder
  916. var quote byte
  917. for i := 0; i < len(query); {
  918. ch := query[i]
  919. if quote != 0 {
  920. result.WriteByte(ch)
  921. i++
  922. if ch == quote {
  923. if i < len(query) && query[i] == quote {
  924. result.WriteByte(query[i])
  925. i++
  926. } else {
  927. quote = 0
  928. }
  929. }
  930. continue
  931. }
  932. if i+1 < len(query) && ch == '-' && query[i+1] == '-' {
  933. end := strings.IndexByte(query[i:], '\n')
  934. if end < 0 {
  935. result.WriteString(query[i:])
  936. break
  937. }
  938. result.WriteString(query[i : i+end+1])
  939. i += end + 1
  940. continue
  941. }
  942. if i+1 < len(query) && ch == '/' && query[i+1] == '*' {
  943. end := strings.Index(query[i+2:], "*/")
  944. if end < 0 {
  945. result.WriteString(query[i:])
  946. break
  947. }
  948. result.WriteString(query[i : i+end+4])
  949. i += end + 4
  950. continue
  951. }
  952. if ch == '\'' || ch == '"' || ch == '`' || ch == '[' {
  953. quote = ch
  954. if ch == '[' {
  955. quote = ']'
  956. }
  957. result.WriteByte(ch)
  958. i++
  959. continue
  960. }
  961. if ch == '$' && i+1 < len(query) && query[i+1] >= '0' && query[i+1] <= '9' {
  962. end := i + 1
  963. for end < len(query) && query[end] >= '0' && query[end] <= '9' {
  964. end++
  965. }
  966. n, err := strconv.Atoi(query[i+1 : end])
  967. if err != nil || n < 1 || n > len(params) {
  968. return "", fmt.Errorf("parameter %s was not provided", query[i:end])
  969. }
  970. literal, err := parameterLiteral(params[n-1])
  971. if err != nil {
  972. return "", fmt.Errorf("parameter $%d: %w", n, err)
  973. }
  974. result.WriteString(literal)
  975. i = end
  976. continue
  977. }
  978. result.WriteByte(ch)
  979. i++
  980. }
  981. return result.String(), nil
  982. }
  983. func parameterLiteral(param boundParameter) (string, error) {
  984. if param.null {
  985. return "NULL", nil
  986. }
  987. if param.format == 1 {
  988. switch param.oid {
  989. case 16:
  990. if len(param.value) != 1 {
  991. return "", fmt.Errorf("invalid binary boolean")
  992. }
  993. if param.value[0] == 0 {
  994. return "FALSE", nil
  995. }
  996. return "TRUE", nil
  997. case 21:
  998. if len(param.value) != 2 {
  999. return "", fmt.Errorf("invalid binary int2")
  1000. }
  1001. return strconv.FormatInt(int64(int16(binary.BigEndian.Uint16(param.value))), 10), nil
  1002. case 23:
  1003. if len(param.value) != 4 {
  1004. return "", fmt.Errorf("invalid binary int4")
  1005. }
  1006. return strconv.FormatInt(int64(int32(binary.BigEndian.Uint32(param.value))), 10), nil
  1007. case 20:
  1008. if len(param.value) != 8 {
  1009. return "", fmt.Errorf("invalid binary int8")
  1010. }
  1011. return strconv.FormatInt(int64(binary.BigEndian.Uint64(param.value)), 10), nil
  1012. default:
  1013. return "", fmt.Errorf("%w: binary parameter format for OID %d", pgerror.ErrFeatureNotSupported, param.oid)
  1014. }
  1015. }
  1016. value := string(param.value)
  1017. switch param.oid {
  1018. case 0:
  1019. if strings.EqualFold(value, "true") || strings.EqualFold(value, "false") {
  1020. return strings.ToUpper(value), nil
  1021. }
  1022. if _, err := strconv.ParseFloat(value, 64); err == nil && value != "" {
  1023. return value, nil
  1024. }
  1025. return "'" + strings.ReplaceAll(value, "'", "''") + "'", nil
  1026. case 16:
  1027. if strings.EqualFold(value, "true") || value == "1" || value == "t" {
  1028. return "TRUE", nil
  1029. }
  1030. return "FALSE", nil
  1031. case 20, 21, 23, 26, 700, 701, 1700:
  1032. if _, err := strconv.ParseFloat(value, 64); err != nil {
  1033. return "", fmt.Errorf("invalid numeric value")
  1034. }
  1035. return value, nil
  1036. default:
  1037. return "'" + strings.ReplaceAll(value, "'", "''") + "'", nil
  1038. }
  1039. }
  1040. // sendResult sends query results
  1041. func (c *Connection) sendResult(result *executor.Result, stmt parser.Statement) error {
  1042. // Any statement that produced a row set (SELECT, or INSERT/UPDATE/DELETE
  1043. // with RETURNING) sends a row description and its data rows. Other
  1044. // statements only send the command completion tag.
  1045. if len(result.Columns) > 0 {
  1046. if err := c.sendRowDescription(result.Columns, wireColumnTypes(result)); err != nil {
  1047. return err
  1048. }
  1049. for _, row := range result.Rows {
  1050. if err := c.sendDataRow(row, result.Columns); err != nil {
  1051. return err
  1052. }
  1053. }
  1054. return c.sendCommandComplete(c.getCommandTag(stmt, result))
  1055. }
  1056. // For other statements, just send command complete
  1057. tag := c.getCommandTag(stmt, result)
  1058. return c.sendCommandComplete(tag)
  1059. }
  1060. // wireColumnTypes corrects declared-affinity metadata when SQLite has stored a
  1061. // value of another type. In particular, binding []byte to a VARCHAR column is
  1062. // still a BLOB in SQLite; advertising TEXT while encoding PostgreSQL bytea text
  1063. // would make clients receive the literal "\\x..." instead of the original
  1064. // bytes.
  1065. func wireColumnTypes(result *executor.Result) []string {
  1066. types := append([]string(nil), result.ColumnTypes...)
  1067. if len(types) < len(result.Columns) {
  1068. types = append(types, make([]string, len(result.Columns)-len(types))...)
  1069. }
  1070. for _, row := range result.Rows {
  1071. for i, value := range row {
  1072. if i >= len(types) {
  1073. break
  1074. }
  1075. if _, ok := value.([]byte); ok {
  1076. types[i] = "BLOB"
  1077. }
  1078. }
  1079. }
  1080. return types
  1081. }
  1082. // getCommandTag returns the command completion tag
  1083. func (c *Connection) getCommandTag(stmt parser.Statement, result *executor.Result) string {
  1084. switch s := stmt.(type) {
  1085. case *parser.SelectStmt:
  1086. return fmt.Sprintf("SELECT %d", len(result.Rows))
  1087. case *parser.CreateTableStmt:
  1088. return "CREATE TABLE"
  1089. case *parser.DropTableStmt:
  1090. return "DROP TABLE"
  1091. case *parser.CreateIndexStmt:
  1092. return "CREATE INDEX"
  1093. case *parser.DropIndexStmt:
  1094. return "DROP INDEX"
  1095. case *parser.AlterTableStmt:
  1096. return "ALTER TABLE"
  1097. case *parser.InsertStmt:
  1098. return fmt.Sprintf("INSERT 0 %d", result.RowsAffected)
  1099. case *parser.UpdateStmt:
  1100. return fmt.Sprintf("UPDATE %d", result.RowsAffected)
  1101. case *parser.DeleteStmt:
  1102. return fmt.Sprintf("DELETE %d", result.RowsAffected)
  1103. case *parser.BeginStmt:
  1104. c.txStatus = TxStatusInBlock
  1105. return "BEGIN"
  1106. case *parser.CommitStmt:
  1107. c.txStatus = TxStatusIdle
  1108. return "COMMIT"
  1109. case *parser.RollbackStmt:
  1110. if s.Savepoint != "" {
  1111. c.txStatus = TxStatusInBlock
  1112. return "ROLLBACK"
  1113. }
  1114. c.txStatus = TxStatusIdle
  1115. return "ROLLBACK"
  1116. case *parser.SavepointStmt:
  1117. c.txStatus = TxStatusInBlock
  1118. return "SAVEPOINT"
  1119. case *parser.ReleaseStmt:
  1120. c.txStatus = TxStatusInBlock
  1121. return "RELEASE"
  1122. case *parser.ListenStmt:
  1123. return "LISTEN"
  1124. case *parser.UnlistenStmt:
  1125. return "UNLISTEN"
  1126. case *parser.NotifyStmt:
  1127. return "NOTIFY"
  1128. default:
  1129. return "OK"
  1130. }
  1131. }
  1132. // sendAuthenticationOk sends authentication OK message
  1133. func (c *Connection) sendAuthenticationOk() error {
  1134. mb := NewMessageBuilder()
  1135. mb.WriteInt32(0) // Auth OK
  1136. return c.writeMessage(MsgAuthenticationOk, mb.Bytes())
  1137. }
  1138. // drainNotifications writes every notification currently buffered for this
  1139. // session. It is called at protocol-safe points (after Sync/ReadyForQuery).
  1140. func (c *Connection) drainNotifications() error {
  1141. ch := c.executor.NotificationChannel()
  1142. for {
  1143. select {
  1144. case n := <-ch:
  1145. if err := c.sendNotification(n); err != nil {
  1146. return err
  1147. }
  1148. default:
  1149. return c.writer.Flush()
  1150. }
  1151. }
  1152. }
  1153. // sendNotification writes a NotificationResponse frame. The frame is only
  1154. // written by the connection's main goroutine, never from a publisher.
  1155. func (c *Connection) sendNotification(n storage.Notification) error {
  1156. mb := NewMessageBuilder()
  1157. mb.WriteInt32(n.PID)
  1158. mb.WriteString(n.Channel)
  1159. mb.WriteString(n.Payload)
  1160. return c.writeMessage(MsgNotificationResponse, mb.Bytes())
  1161. }
  1162. // sendLSN exposes the last commit LSN as a ParameterStatus. Drivers that do
  1163. // not know the key ignore it; subscribers can use it as an ordering cursor.
  1164. func (c *Connection) sendLSN(lsn uint64) error {
  1165. return c.sendParameterStatus("pizzasql.lsn", strconv.FormatUint(lsn, 10))
  1166. }
  1167. // sendParameterStatus sends a parameter status message
  1168. func (c *Connection) sendParameterStatus(name, value string) error {
  1169. mb := NewMessageBuilder()
  1170. mb.WriteString(name)
  1171. mb.WriteString(value)
  1172. return c.writeMessage(MsgParameterStatus, mb.Bytes())
  1173. }
  1174. // sendBackendKeyData sends backend key data
  1175. func (c *Connection) sendBackendKeyData(processID, secretKey int32) error {
  1176. mb := NewMessageBuilder()
  1177. mb.WriteInt32(processID)
  1178. mb.WriteInt32(secretKey)
  1179. return c.writeMessage(MsgBackendKeyData, mb.Bytes())
  1180. }
  1181. // sendReadyForQuery sends ready for query message
  1182. func (c *Connection) sendReadyForQuery() error {
  1183. mb := NewMessageBuilder()
  1184. mb.AppendByte(c.txStatus)
  1185. if err := c.writeMessage(MsgReadyForQuery, mb.Bytes()); err != nil {
  1186. return err
  1187. }
  1188. // ReadyForQuery closes out a response cycle, so flush everything buffered
  1189. // so far. This is what makes simple-query results and Sync responses
  1190. // visible to the client.
  1191. return c.writer.Flush()
  1192. }
  1193. // sendEmptyQueryResponse sends empty query response
  1194. func (c *Connection) sendEmptyQueryResponse() error {
  1195. return c.writeMessage(MsgEmptyQueryResponse, []byte{})
  1196. }
  1197. // sendRowDescription sends row description (column metadata)
  1198. func (c *Connection) sendRowDescription(columns []string, columnTypes []string) error {
  1199. mb := NewMessageBuilder()
  1200. mb.WriteInt16(int16(len(columns)))
  1201. for i, col := range columns {
  1202. colType := ""
  1203. if i < len(columnTypes) {
  1204. colType = columnTypes[i]
  1205. }
  1206. mb.WriteString(col)
  1207. mb.WriteInt32(0) // table OID
  1208. mb.WriteInt16(0) // column attribute number
  1209. mb.WriteInt32(c.getOIDForType(colType)) // type OID
  1210. mb.WriteInt16(c.getTypeSizeForType(colType)) // type size
  1211. mb.WriteInt32(-1) // type modifier
  1212. mb.WriteInt16(0) // format code (text)
  1213. }
  1214. return c.writeMessage(MsgRowDescription, mb.Bytes())
  1215. }
  1216. // sendDataRow sends a data row
  1217. func (c *Connection) sendDataRow(row []interface{}, columns []string) error {
  1218. mb := NewMessageBuilder()
  1219. mb.WriteInt16(int16(len(row)))
  1220. for _, value := range row {
  1221. if value == nil {
  1222. mb.WriteInt32(-1) // NULL indicator
  1223. continue
  1224. }
  1225. // Convert value to string
  1226. strValue := c.valueToString(value)
  1227. mb.WriteInt32(int32(len(strValue)))
  1228. mb.WriteBytes([]byte(strValue))
  1229. }
  1230. return c.writeMessage(MsgDataRow, mb.Bytes())
  1231. }
  1232. // sendCommandComplete sends command complete message
  1233. func (c *Connection) sendCommandComplete(tag string) error {
  1234. mb := NewMessageBuilder()
  1235. mb.WriteString(tag)
  1236. return c.writeMessage(MsgCommandComplete, mb.Bytes())
  1237. }
  1238. // sendError sends an error response
  1239. func (c *Connection) sendError(severity, code, message string) error {
  1240. if severity == "ERROR" && c.txStatus == TxStatusInBlock {
  1241. c.txStatus = TxStatusFailed
  1242. }
  1243. mb := NewMessageBuilder()
  1244. mb.AppendByte(ErrorFieldSeverity)
  1245. mb.WriteString(severity)
  1246. mb.AppendByte(ErrorFieldCode)
  1247. mb.WriteString(code)
  1248. mb.AppendByte(ErrorFieldMessage)
  1249. mb.WriteString(message)
  1250. mb.AppendByte(0) // Terminator
  1251. if err := c.writeMessage(MsgErrorResponse, mb.Bytes()); err != nil {
  1252. return err
  1253. }
  1254. // Errors must be visible promptly, including FATAL startup failures that
  1255. // are not followed by a ReadyForQuery before the connection closes.
  1256. return c.writer.Flush()
  1257. }
  1258. // writeMessage buffers a message for the connection. It does not flush, so
  1259. // callers that need to make a response visible to the client must flush at the
  1260. // appropriate protocol boundary (ReadyForQuery, an explicit Flush message, or
  1261. // an error response). Buffering amortizes the per-message syscalls that a
  1262. // result set would otherwise incur; the underlying bufio.Writer bounds memory
  1263. // use so large result sets cannot grow the buffer without limit.
  1264. func (c *Connection) writeMessage(msgType byte, data []byte) error {
  1265. if !c.quiet {
  1266. log.Printf("Sending message type=%c length=%d", msgType, len(data)+4)
  1267. }
  1268. return WriteMessage(c.writer, msgType, data)
  1269. }
  1270. // getOIDForType returns PostgreSQL OID for type
  1271. func (c *Connection) getOIDForType(typeName string) int32 {
  1272. switch strings.ToUpper(typeName) {
  1273. case "INTEGER", "INT":
  1274. return 23 // INT4OID
  1275. case "BIGINT":
  1276. return 20 // INT8OID
  1277. case "TEXT", "VARCHAR", "CHAR", "UUID":
  1278. // UUID is stored as text (SQLite-style), so it reports TEXTOID rather
  1279. // than the native PG UUID OID.
  1280. return 25 // TEXTOID
  1281. case "REAL", "FLOAT":
  1282. return 700 // FLOAT4OID
  1283. case "DOUBLE":
  1284. return 701 // FLOAT8OID
  1285. case "BOOLEAN", "BOOL":
  1286. return 16 // BOOLOID
  1287. case "BLOB":
  1288. return 17 // BYTEAOID
  1289. case "DATETIME", "TIMESTAMP":
  1290. // Datetime values are exchanged as UTC RFC3339 (ISO8601 with a timezone
  1291. // offset), which timestamptz decodes directly.
  1292. return 1184 // TIMESTAMPTZOID
  1293. case "DATE":
  1294. return 1082 // DATEOID
  1295. default:
  1296. return 25 // Default to TEXT
  1297. }
  1298. }
  1299. // getTypeSizeForType returns type size
  1300. func (c *Connection) getTypeSizeForType(typeName string) int16 {
  1301. switch strings.ToUpper(typeName) {
  1302. case "INTEGER", "INT":
  1303. return 4
  1304. case "BIGINT":
  1305. return 8
  1306. case "REAL", "FLOAT":
  1307. return 4
  1308. case "DOUBLE":
  1309. return 8
  1310. case "BOOLEAN", "BOOL":
  1311. return 1
  1312. case "DATETIME", "TIMESTAMP":
  1313. return 8
  1314. case "DATE":
  1315. return 4
  1316. default:
  1317. return -1 // Variable length
  1318. }
  1319. }
  1320. // valueToString converts a value to string
  1321. func (c *Connection) valueToString(value interface{}) string {
  1322. if value == nil {
  1323. return ""
  1324. }
  1325. // PostgreSQL's text format for bytea is \x followed by hex. Emitting that
  1326. // lets libpq/pgx decode a BLOB column (OID 17) losslessly.
  1327. if b, ok := value.([]byte); ok {
  1328. return `\x` + hex.EncodeToString(b)
  1329. }
  1330. return fmt.Sprintf("%v", value)
  1331. }
  1332. // handleVersionQuery handles SELECT version()
  1333. func (c *Connection) handleVersionQuery() error {
  1334. columns := []string{"version"}
  1335. columnTypes := []string{"TEXT"}
  1336. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1337. return err
  1338. }
  1339. row := []interface{}{"PostgreSQL " + version.PostgreSQLCompatVersion + " (PizzaSQL)"}
  1340. if err := c.sendDataRow(row, columns); err != nil {
  1341. return err
  1342. }
  1343. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1344. return err
  1345. }
  1346. return c.sendReadyForQuery()
  1347. }
  1348. // handleCurrentUserQuery handles SELECT current_user
  1349. func (c *Connection) handleCurrentUserQuery() error {
  1350. columns := []string{"current_user"}
  1351. columnTypes := []string{"TEXT"}
  1352. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1353. return err
  1354. }
  1355. user := c.params["user"]
  1356. if user == "" {
  1357. user = "pizzasql"
  1358. }
  1359. row := []interface{}{user}
  1360. if err := c.sendDataRow(row, columns); err != nil {
  1361. return err
  1362. }
  1363. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1364. return err
  1365. }
  1366. return c.sendReadyForQuery()
  1367. }
  1368. // handleShowCommand handles SHOW commands
  1369. func (c *Connection) handleShowCommand(sqlUpper string) error {
  1370. var value string
  1371. var name string
  1372. if sqlUpper == "SERVER_VERSION" {
  1373. name = "server_version"
  1374. value = version.PostgreSQLCompatVersion
  1375. } else if sqlUpper == "SERVER_ENCODING" {
  1376. name = "server_encoding"
  1377. value = "UTF8"
  1378. } else if sqlUpper == "CLIENT_ENCODING" {
  1379. name = "client_encoding"
  1380. value = "UTF8"
  1381. } else {
  1382. // Unknown SHOW command
  1383. c.sendError("ERROR", ErrCodeFeatureNotSupported, "SHOW command not supported")
  1384. return c.sendReadyForQuery()
  1385. }
  1386. columns := []string{name}
  1387. columnTypes := []string{"TEXT"}
  1388. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1389. return err
  1390. }
  1391. row := []interface{}{value}
  1392. if err := c.sendDataRow(row, columns); err != nil {
  1393. return err
  1394. }
  1395. if err := c.sendCommandComplete("SHOW"); err != nil {
  1396. return err
  1397. }
  1398. return c.sendReadyForQuery()
  1399. }