connection.go 37 KB

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