connection.go 37 KB

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