connection.go 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  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. if errors.Is(err, storage.ErrSerialization) {
  286. code = ErrCodeSerializationFailure
  287. c.txStatus = TxStatusIdle
  288. } else if _, commit := stmt.(*parser.CommitStmt); commit {
  289. // A failed COMMIT has already rolled the transaction back in
  290. // storage; leaving the session in the failed state would make
  291. // every following statement (including ROLLBACK) fail.
  292. c.txStatus = TxStatusIdle
  293. } else if c.txStatus == TxStatusInBlock {
  294. c.txStatus = TxStatusFailed
  295. }
  296. c.sendError("ERROR", code, fmt.Sprintf("Execution error: %v", err))
  297. return c.sendReadyForQuery()
  298. }
  299. if err := c.sendResult(result, stmt); err != nil {
  300. return err
  301. }
  302. }
  303. return c.sendReadyForQuery()
  304. }
  305. func (c *Connection) handleParse(msg *Message) error {
  306. if c.extendedFailed {
  307. return nil
  308. }
  309. name, pos, err := readCString(msg.Data, 0)
  310. if err != nil {
  311. return c.failExtended(ErrCodeProtocolViolation, err)
  312. }
  313. query, pos, err := readCString(msg.Data, pos)
  314. if err != nil || pos+2 > len(msg.Data) {
  315. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Parse message"))
  316. }
  317. count := int(binary.BigEndian.Uint16(msg.Data[pos : pos+2]))
  318. pos += 2
  319. if pos+count*4 != len(msg.Data) {
  320. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Parse parameter list"))
  321. }
  322. oids := make([]int32, count)
  323. for i := range oids {
  324. oids[i] = int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  325. pos += 4
  326. }
  327. c.statements[name] = &preparedStatement{query: query, paramOIDs: oids}
  328. return c.writeMessage(MsgParseComplete, nil)
  329. }
  330. func (c *Connection) handleBind(msg *Message) error {
  331. if c.extendedFailed {
  332. return nil
  333. }
  334. portalName, pos, err := readCString(msg.Data, 0)
  335. if err != nil {
  336. return c.failExtended(ErrCodeProtocolViolation, err)
  337. }
  338. statementName, pos, err := readCString(msg.Data, pos)
  339. if err != nil {
  340. return c.failExtended(ErrCodeProtocolViolation, err)
  341. }
  342. statement, ok := c.statements[statementName]
  343. if !ok {
  344. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("prepared statement %q does not exist", statementName))
  345. }
  346. formats, pos, err := readInt16List(msg.Data, pos)
  347. if err != nil || pos+2 > len(msg.Data) {
  348. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind format list"))
  349. }
  350. paramCount := int(binary.BigEndian.Uint16(msg.Data[pos : pos+2]))
  351. pos += 2
  352. params := make([]boundParameter, paramCount)
  353. for i := range params {
  354. if pos+4 > len(msg.Data) {
  355. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter"))
  356. }
  357. length := int32(binary.BigEndian.Uint32(msg.Data[pos : pos+4]))
  358. pos += 4
  359. params[i].oid = parameterOID(statement.paramOIDs, i)
  360. params[i].format = parameterFormat(formats, i)
  361. if length == -1 {
  362. params[i].null = true
  363. continue
  364. }
  365. if length < 0 || pos+int(length) > len(msg.Data) {
  366. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind parameter length"))
  367. }
  368. params[i].value = append([]byte(nil), msg.Data[pos:pos+int(length)]...)
  369. pos += int(length)
  370. }
  371. _, pos, err = readInt16List(msg.Data, pos) // result formats; text output is currently used
  372. if err != nil || pos != len(msg.Data) {
  373. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Bind result format list"))
  374. }
  375. query, err := bindQuery(statement.query, params)
  376. if err != nil {
  377. return c.failExtended(ErrCodeInvalidParameter, err)
  378. }
  379. c.portals[portalName] = &portal{query: query}
  380. return c.writeMessage(MsgBindComplete, nil)
  381. }
  382. func (c *Connection) handleDescribe(msg *Message) error {
  383. if c.extendedFailed {
  384. return nil
  385. }
  386. if len(msg.Data) < 2 {
  387. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe message"))
  388. }
  389. name, pos, err := readCString(msg.Data, 1)
  390. if err != nil || pos != len(msg.Data) {
  391. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe name"))
  392. }
  393. switch msg.Data[0] {
  394. case 'S':
  395. statement, ok := c.statements[name]
  396. if !ok {
  397. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("prepared statement %q does not exist", name))
  398. }
  399. mb := NewMessageBuilder()
  400. mb.WriteInt16(int16(len(statement.paramOIDs)))
  401. for _, oid := range statement.paramOIDs {
  402. mb.WriteInt32(oid)
  403. }
  404. if err := c.writeMessage(MsgParameterDescription, mb.Bytes()); err != nil {
  405. return err
  406. }
  407. case 'P':
  408. if _, ok := c.portals[name]; !ok {
  409. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("portal %q does not exist", name))
  410. }
  411. default:
  412. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Describe target"))
  413. }
  414. // Execute sends the row description once the bound statement has been
  415. // analyzed, avoiding side effects during Describe.
  416. return c.writeMessage(MsgNoData, nil)
  417. }
  418. func (c *Connection) handleExecute(msg *Message) error {
  419. if c.extendedFailed {
  420. return nil
  421. }
  422. name, pos, err := readCString(msg.Data, 0)
  423. if err != nil || pos+4 != len(msg.Data) {
  424. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Execute message"))
  425. }
  426. portal, ok := c.portals[name]
  427. if !ok {
  428. return c.failExtended(ErrCodeInvalidParameter, fmt.Errorf("portal %q does not exist", name))
  429. }
  430. if portal.executed {
  431. return c.failExtended(ErrCodeFeatureNotSupported, fmt.Errorf("portal can only be executed once"))
  432. }
  433. portal.executed = true
  434. // Check the transaction state before catalog emulation. Catalog queries do
  435. // not all parse as regular PizzaSQL statements, but must still return 25P02
  436. // while the transaction is aborted.
  437. if c.txStatus == TxStatusFailed && !isRollbackStatement(portal.query) {
  438. return c.failExtended(ErrCodeTransactionAborted, fmt.Errorf("current transaction is aborted, commands ignored until end of transaction block"))
  439. }
  440. if result, handled, catalogErr := c.catalogResult(portal.query); handled {
  441. if catalogErr != nil {
  442. return c.failExtended(ErrCodeInternalError, catalogErr)
  443. }
  444. return c.sendTabularResult(result, "SELECT")
  445. }
  446. l := lexer.New(portal.query)
  447. stmt, err := parser.New(l).Parse()
  448. if err != nil {
  449. return c.failExtended(ErrCodeSyntaxError, fmt.Errorf("syntax error: %w", err))
  450. }
  451. result, err := c.executor.Execute(stmt)
  452. if err != nil {
  453. code := ErrCodeInternalError
  454. if errors.Is(err, storage.ErrSerialization) {
  455. code = ErrCodeSerializationFailure
  456. c.txStatus = TxStatusIdle
  457. } else if _, commit := stmt.(*parser.CommitStmt); commit {
  458. c.txStatus = TxStatusIdle
  459. } else if c.txStatus == TxStatusInBlock {
  460. c.txStatus = TxStatusFailed
  461. }
  462. return c.failExtended(code, fmt.Errorf("execution error: %w", err))
  463. }
  464. return c.sendResult(result, stmt)
  465. }
  466. var catalogFilterPattern = regexp.MustCompile(`(?i)\b(table_name|tablename|table_schema|schemaname|constraint_name|indexname)\s*=\s*'((?:''|[^'])*)'`)
  467. func (c *Connection) catalogResult(sql string) (*executor.Result, bool, error) {
  468. if !isSingleStatementSQL(sql) {
  469. return nil, false, nil
  470. }
  471. upper := strings.ToUpper(sql)
  472. var source string
  473. for _, candidate := range []string{
  474. "INFORMATION_SCHEMA.TABLES", "INFORMATION_SCHEMA.COLUMNS",
  475. "INFORMATION_SCHEMA.TABLE_CONSTRAINTS", "INFORMATION_SCHEMA.KEY_COLUMN_USAGE",
  476. "PG_TABLES", "PG_INDEXES",
  477. } {
  478. if strings.Contains(upper, "FROM "+candidate) {
  479. source = candidate
  480. break
  481. }
  482. }
  483. if source == "" {
  484. return nil, false, nil
  485. }
  486. if c.txStatus == TxStatusIdle {
  487. c.schema.LockStatement()
  488. defer c.schema.UnlockStatement()
  489. }
  490. tables, err := c.schema.ListTables()
  491. if err != nil {
  492. return nil, true, err
  493. }
  494. rows := make([]map[string]interface{}, 0)
  495. switch source {
  496. case "INFORMATION_SCHEMA.TABLES":
  497. for _, table := range tables {
  498. rows = append(rows, map[string]interface{}{
  499. "table_catalog": c.database, "table_schema": "public", "table_name": table, "table_type": "BASE TABLE",
  500. })
  501. }
  502. case "PG_TABLES":
  503. for _, table := range tables {
  504. indexes, _ := c.schema.ListTableIndexes(table)
  505. rows = append(rows, map[string]interface{}{
  506. "schemaname": "public", "tablename": table, "tableowner": c.params["user"], "tablespace": nil,
  507. "hasindexes": len(indexes) > 0, "hasrules": false, "hastriggers": false, "rowsecurity": false,
  508. })
  509. }
  510. case "INFORMATION_SCHEMA.COLUMNS":
  511. for _, table := range tables {
  512. schema, schemaErr := c.schema.GetSchema(table)
  513. if schemaErr != nil {
  514. continue
  515. }
  516. for i, column := range schema.Columns {
  517. rows = append(rows, map[string]interface{}{
  518. "table_catalog": c.database, "table_schema": "public", "table_name": table,
  519. "column_name": column.Name, "ordinal_position": int64(i + 1), "column_default": column.Default,
  520. "is_nullable": yesNo(column.Nullable), "data_type": strings.ToLower(column.Type),
  521. })
  522. }
  523. }
  524. case "INFORMATION_SCHEMA.TABLE_CONSTRAINTS", "INFORMATION_SCHEMA.KEY_COLUMN_USAGE":
  525. for _, table := range tables {
  526. schema, schemaErr := c.schema.GetSchema(table)
  527. if schemaErr != nil || schema.PrimaryKey == "" || schema.PrimaryKey == "_rowid_" {
  528. continue
  529. }
  530. row := map[string]interface{}{
  531. "constraint_catalog": c.database, "constraint_schema": "public", "constraint_name": table + "_pkey",
  532. "table_catalog": c.database, "table_schema": "public", "table_name": table,
  533. }
  534. if source == "INFORMATION_SCHEMA.TABLE_CONSTRAINTS" {
  535. row["constraint_type"] = "PRIMARY KEY"
  536. row["is_deferrable"] = "NO"
  537. row["initially_deferred"] = "NO"
  538. } else {
  539. row["column_name"] = schema.PrimaryKey
  540. row["ordinal_position"] = int64(1)
  541. }
  542. rows = append(rows, row)
  543. }
  544. case "PG_INDEXES":
  545. for _, table := range tables {
  546. indexes, _ := c.schema.ListTableIndexes(table)
  547. for _, index := range indexes {
  548. columns := make([]string, len(index.Columns))
  549. for i, column := range index.Columns {
  550. columns[i] = column.Name
  551. }
  552. unique := ""
  553. if index.Unique {
  554. unique = "UNIQUE "
  555. }
  556. rows = append(rows, map[string]interface{}{
  557. "schemaname": "public", "tablename": table, "indexname": index.Name, "tablespace": nil,
  558. "indexdef": fmt.Sprintf("CREATE %sINDEX %s ON %s (%s)", unique, index.Name, table, strings.Join(columns, ", ")),
  559. })
  560. }
  561. }
  562. }
  563. for _, match := range catalogFilterPattern.FindAllStringSubmatch(sql, -1) {
  564. column, expected := strings.ToLower(match[1]), strings.ReplaceAll(match[2], "''", "'")
  565. filtered := rows[:0]
  566. for _, row := range rows {
  567. if value, ok := row[column]; ok && strings.EqualFold(fmt.Sprintf("%v", value), expected) {
  568. filtered = append(filtered, row)
  569. }
  570. }
  571. rows = filtered
  572. }
  573. columns := catalogProjection(sql, rows)
  574. result := executor.NewResult("SELECT")
  575. if len(columns) == 1 && columns[0] == "count(*)" {
  576. result.AddColumnWithType("count", "INTEGER")
  577. result.AddRow(int64(len(rows)))
  578. return result, true, nil
  579. }
  580. for _, column := range columns {
  581. columnType := "TEXT"
  582. if column == "ordinal_position" {
  583. columnType = "INTEGER"
  584. } else if strings.HasPrefix(column, "has") || column == "rowsecurity" {
  585. columnType = "BOOLEAN"
  586. }
  587. result.AddColumnWithType(column, columnType)
  588. }
  589. for _, row := range rows {
  590. values := make([]interface{}, len(columns))
  591. for i, column := range columns {
  592. values[i] = row[column]
  593. }
  594. result.AddRow(values...)
  595. }
  596. return result, true, nil
  597. }
  598. func isSingleStatementSQL(sql string) bool {
  599. trimmed := strings.TrimSpace(sql)
  600. if strings.HasSuffix(trimmed, ";") {
  601. trimmed = strings.TrimSpace(strings.TrimSuffix(trimmed, ";"))
  602. }
  603. inString, inIdent := false, false
  604. for i := 0; i < len(trimmed); i++ {
  605. switch trimmed[i] {
  606. case '\'':
  607. if !inIdent {
  608. if inString && i+1 < len(trimmed) && trimmed[i+1] == '\'' {
  609. i++
  610. continue
  611. }
  612. inString = !inString
  613. }
  614. case '"':
  615. if !inString {
  616. inIdent = !inIdent
  617. }
  618. case ';':
  619. if !inString && !inIdent {
  620. return false
  621. }
  622. }
  623. }
  624. return true
  625. }
  626. // isRollbackStatement reports whether sql parses as a single ROLLBACK
  627. // statement, including ROLLBACK TO SAVEPOINT.
  628. func isRollbackStatement(sql string) bool {
  629. stmt, err := parser.New(lexer.New(sql)).Parse()
  630. if err != nil {
  631. return false
  632. }
  633. _, ok := stmt.(*parser.RollbackStmt)
  634. return ok
  635. }
  636. func catalogProjection(sql string, rows []map[string]interface{}) []string {
  637. upper := strings.ToUpper(sql)
  638. selectPos, fromPos := strings.Index(upper, "SELECT"), strings.Index(upper, " FROM ")
  639. if selectPos < 0 || fromPos < 0 || fromPos <= selectPos+6 {
  640. return nil
  641. }
  642. projection := strings.TrimSpace(sql[selectPos+6 : fromPos])
  643. projection = strings.TrimSpace(strings.TrimPrefix(strings.ToUpper(projection), "DISTINCT "))
  644. if projection == "*" && len(rows) > 0 {
  645. columns := make([]string, 0, len(rows[0]))
  646. for column := range rows[0] {
  647. columns = append(columns, column)
  648. }
  649. sort.Strings(columns)
  650. return columns
  651. }
  652. parts := strings.Split(projection, ",")
  653. columns := make([]string, 0, len(parts))
  654. for _, part := range parts {
  655. column := strings.TrimSpace(part)
  656. if index := strings.Index(strings.ToUpper(column), " AS "); index >= 0 {
  657. column = strings.TrimSpace(column[:index])
  658. }
  659. if index := strings.LastIndex(column, "."); index >= 0 {
  660. column = column[index+1:]
  661. }
  662. columns = append(columns, strings.ToLower(strings.Trim(column, `"`)))
  663. }
  664. return columns
  665. }
  666. func yesNo(value bool) string {
  667. if value {
  668. return "YES"
  669. }
  670. return "NO"
  671. }
  672. func (c *Connection) sendTabularResult(result *executor.Result, tag string) error {
  673. if err := c.sendRowDescription(result.Columns, result.ColumnTypes); err != nil {
  674. return err
  675. }
  676. for _, row := range result.Rows {
  677. if err := c.sendDataRow(row, result.Columns); err != nil {
  678. return err
  679. }
  680. }
  681. return c.sendCommandComplete(fmt.Sprintf("%s %d", tag, len(result.Rows)))
  682. }
  683. func (c *Connection) handleClose(msg *Message) error {
  684. if c.extendedFailed {
  685. return nil
  686. }
  687. if len(msg.Data) < 2 {
  688. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close message"))
  689. }
  690. name, pos, err := readCString(msg.Data, 1)
  691. if err != nil || pos != len(msg.Data) {
  692. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close name"))
  693. }
  694. if msg.Data[0] == 'S' {
  695. delete(c.statements, name)
  696. } else if msg.Data[0] == 'P' {
  697. delete(c.portals, name)
  698. } else {
  699. return c.failExtended(ErrCodeProtocolViolation, fmt.Errorf("invalid Close target"))
  700. }
  701. return c.writeMessage(MsgCloseComplete, nil)
  702. }
  703. func (c *Connection) failExtended(code string, err error) error {
  704. c.extendedFailed = true
  705. return c.sendError("ERROR", code, err.Error())
  706. }
  707. type boundParameter struct {
  708. value []byte
  709. oid int32
  710. format int16
  711. null bool
  712. }
  713. func readCString(data []byte, pos int) (string, int, error) {
  714. if pos < 0 || pos >= len(data) {
  715. return "", pos, fmt.Errorf("missing null-terminated string")
  716. }
  717. end := bytes.IndexByte(data[pos:], 0)
  718. if end < 0 {
  719. return "", pos, fmt.Errorf("unterminated string")
  720. }
  721. return string(data[pos : pos+end]), pos + end + 1, nil
  722. }
  723. func readInt16List(data []byte, pos int) ([]int16, int, error) {
  724. if pos+2 > len(data) {
  725. return nil, pos, fmt.Errorf("missing list length")
  726. }
  727. count := int(binary.BigEndian.Uint16(data[pos : pos+2]))
  728. pos += 2
  729. if pos+count*2 > len(data) {
  730. return nil, pos, fmt.Errorf("truncated list")
  731. }
  732. result := make([]int16, count)
  733. for i := range result {
  734. result[i] = int16(binary.BigEndian.Uint16(data[pos : pos+2]))
  735. pos += 2
  736. }
  737. return result, pos, nil
  738. }
  739. func parameterOID(oids []int32, index int) int32 {
  740. if index < len(oids) {
  741. return oids[index]
  742. }
  743. return 0
  744. }
  745. func parameterFormat(formats []int16, index int) int16 {
  746. if len(formats) == 1 {
  747. return formats[0]
  748. }
  749. if index < len(formats) {
  750. return formats[index]
  751. }
  752. return 0
  753. }
  754. func bindQuery(query string, params []boundParameter) (string, error) {
  755. var result strings.Builder
  756. inString, inIdent := false, false
  757. for i := 0; i < len(query); {
  758. ch := query[i]
  759. if ch == '\'' && !inIdent {
  760. result.WriteByte(ch)
  761. if inString && i+1 < len(query) && query[i+1] == '\'' {
  762. result.WriteByte(query[i+1])
  763. i += 2
  764. continue
  765. }
  766. inString = !inString
  767. i++
  768. continue
  769. }
  770. if ch == '"' && !inString {
  771. inIdent = !inIdent
  772. result.WriteByte(ch)
  773. i++
  774. continue
  775. }
  776. if ch == '$' && !inString && !inIdent && i+1 < len(query) && query[i+1] >= '0' && query[i+1] <= '9' {
  777. end := i + 1
  778. for end < len(query) && query[end] >= '0' && query[end] <= '9' {
  779. end++
  780. }
  781. n, _ := strconv.Atoi(query[i+1 : end])
  782. if n < 1 || n > len(params) {
  783. return "", fmt.Errorf("parameter $%d was not provided", n)
  784. }
  785. literal, err := parameterLiteral(params[n-1])
  786. if err != nil {
  787. return "", fmt.Errorf("parameter $%d: %w", n, err)
  788. }
  789. result.WriteString(literal)
  790. i = end
  791. continue
  792. }
  793. result.WriteByte(ch)
  794. i++
  795. }
  796. return result.String(), nil
  797. }
  798. func parameterLiteral(param boundParameter) (string, error) {
  799. if param.null {
  800. return "NULL", nil
  801. }
  802. if param.format == 1 {
  803. switch param.oid {
  804. case 16:
  805. if len(param.value) != 1 {
  806. return "", fmt.Errorf("invalid binary boolean")
  807. }
  808. if param.value[0] == 0 {
  809. return "FALSE", nil
  810. }
  811. return "TRUE", nil
  812. case 21:
  813. if len(param.value) != 2 {
  814. return "", fmt.Errorf("invalid binary int2")
  815. }
  816. return strconv.FormatInt(int64(int16(binary.BigEndian.Uint16(param.value))), 10), nil
  817. case 23:
  818. if len(param.value) != 4 {
  819. return "", fmt.Errorf("invalid binary int4")
  820. }
  821. return strconv.FormatInt(int64(int32(binary.BigEndian.Uint32(param.value))), 10), nil
  822. case 20:
  823. if len(param.value) != 8 {
  824. return "", fmt.Errorf("invalid binary int8")
  825. }
  826. return strconv.FormatInt(int64(binary.BigEndian.Uint64(param.value)), 10), nil
  827. default:
  828. return "", fmt.Errorf("binary format is unsupported for OID %d", param.oid)
  829. }
  830. }
  831. value := string(param.value)
  832. switch param.oid {
  833. case 0:
  834. if strings.EqualFold(value, "true") || strings.EqualFold(value, "false") {
  835. return strings.ToUpper(value), nil
  836. }
  837. if _, err := strconv.ParseFloat(value, 64); err == nil && value != "" {
  838. return value, nil
  839. }
  840. return "'" + strings.ReplaceAll(value, "'", "''") + "'", nil
  841. case 16:
  842. if strings.EqualFold(value, "true") || value == "1" || value == "t" {
  843. return "TRUE", nil
  844. }
  845. return "FALSE", nil
  846. case 20, 21, 23, 26, 700, 701, 1700:
  847. if _, err := strconv.ParseFloat(value, 64); err != nil {
  848. return "", fmt.Errorf("invalid numeric value")
  849. }
  850. return value, nil
  851. default:
  852. return "'" + strings.ReplaceAll(value, "'", "''") + "'", nil
  853. }
  854. }
  855. // sendResult sends query results
  856. func (c *Connection) sendResult(result *executor.Result, stmt parser.Statement) error {
  857. // Any statement that produced a row set (SELECT, or INSERT/UPDATE/DELETE
  858. // with RETURNING) sends a row description and its data rows. Other
  859. // statements only send the command completion tag.
  860. if len(result.Columns) > 0 {
  861. if err := c.sendRowDescription(result.Columns, wireColumnTypes(result)); err != nil {
  862. return err
  863. }
  864. for _, row := range result.Rows {
  865. if err := c.sendDataRow(row, result.Columns); err != nil {
  866. return err
  867. }
  868. }
  869. return c.sendCommandComplete(c.getCommandTag(stmt, result))
  870. }
  871. // For other statements, just send command complete
  872. tag := c.getCommandTag(stmt, result)
  873. return c.sendCommandComplete(tag)
  874. }
  875. // wireColumnTypes corrects declared-affinity metadata when SQLite has stored a
  876. // value of another type. In particular, binding []byte to a VARCHAR column is
  877. // still a BLOB in SQLite; advertising TEXT while encoding PostgreSQL bytea text
  878. // would make clients receive the literal "\\x..." instead of the original
  879. // bytes.
  880. func wireColumnTypes(result *executor.Result) []string {
  881. types := append([]string(nil), result.ColumnTypes...)
  882. if len(types) < len(result.Columns) {
  883. types = append(types, make([]string, len(result.Columns)-len(types))...)
  884. }
  885. for _, row := range result.Rows {
  886. for i, value := range row {
  887. if i >= len(types) {
  888. break
  889. }
  890. if _, ok := value.([]byte); ok {
  891. types[i] = "BLOB"
  892. }
  893. }
  894. }
  895. return types
  896. }
  897. // getCommandTag returns the command completion tag
  898. func (c *Connection) getCommandTag(stmt parser.Statement, result *executor.Result) string {
  899. switch s := stmt.(type) {
  900. case *parser.SelectStmt:
  901. return fmt.Sprintf("SELECT %d", len(result.Rows))
  902. case *parser.CreateTableStmt:
  903. return "CREATE TABLE"
  904. case *parser.DropTableStmt:
  905. return "DROP TABLE"
  906. case *parser.CreateIndexStmt:
  907. return "CREATE INDEX"
  908. case *parser.DropIndexStmt:
  909. return "DROP INDEX"
  910. case *parser.AlterTableStmt:
  911. return "ALTER TABLE"
  912. case *parser.InsertStmt:
  913. return fmt.Sprintf("INSERT 0 %d", result.RowsAffected)
  914. case *parser.UpdateStmt:
  915. return fmt.Sprintf("UPDATE %d", result.RowsAffected)
  916. case *parser.DeleteStmt:
  917. return fmt.Sprintf("DELETE %d", result.RowsAffected)
  918. case *parser.BeginStmt:
  919. c.txStatus = TxStatusInBlock
  920. return "BEGIN"
  921. case *parser.CommitStmt:
  922. c.txStatus = TxStatusIdle
  923. return "COMMIT"
  924. case *parser.RollbackStmt:
  925. if s.Savepoint != "" {
  926. c.txStatus = TxStatusInBlock
  927. return "ROLLBACK"
  928. }
  929. c.txStatus = TxStatusIdle
  930. return "ROLLBACK"
  931. case *parser.SavepointStmt:
  932. c.txStatus = TxStatusInBlock
  933. return "SAVEPOINT"
  934. case *parser.ReleaseStmt:
  935. c.txStatus = TxStatusInBlock
  936. return "RELEASE"
  937. default:
  938. return "OK"
  939. }
  940. }
  941. // sendAuthenticationOk sends authentication OK message
  942. func (c *Connection) sendAuthenticationOk() error {
  943. mb := NewMessageBuilder()
  944. mb.WriteInt32(0) // Auth OK
  945. return c.writeMessage(MsgAuthenticationOk, mb.Bytes())
  946. }
  947. // sendParameterStatus sends a parameter status message
  948. func (c *Connection) sendParameterStatus(name, value string) error {
  949. mb := NewMessageBuilder()
  950. mb.WriteString(name)
  951. mb.WriteString(value)
  952. return c.writeMessage(MsgParameterStatus, mb.Bytes())
  953. }
  954. // sendBackendKeyData sends backend key data
  955. func (c *Connection) sendBackendKeyData(processID, secretKey int32) error {
  956. mb := NewMessageBuilder()
  957. mb.WriteInt32(processID)
  958. mb.WriteInt32(secretKey)
  959. return c.writeMessage(MsgBackendKeyData, mb.Bytes())
  960. }
  961. // sendReadyForQuery sends ready for query message
  962. func (c *Connection) sendReadyForQuery() error {
  963. mb := NewMessageBuilder()
  964. mb.AppendByte(c.txStatus)
  965. if err := c.writeMessage(MsgReadyForQuery, mb.Bytes()); err != nil {
  966. return err
  967. }
  968. // ReadyForQuery closes out a response cycle, so flush everything buffered
  969. // so far. This is what makes simple-query results and Sync responses
  970. // visible to the client.
  971. return c.writer.Flush()
  972. }
  973. // sendEmptyQueryResponse sends empty query response
  974. func (c *Connection) sendEmptyQueryResponse() error {
  975. return c.writeMessage(MsgEmptyQueryResponse, []byte{})
  976. }
  977. // sendRowDescription sends row description (column metadata)
  978. func (c *Connection) sendRowDescription(columns []string, columnTypes []string) error {
  979. mb := NewMessageBuilder()
  980. mb.WriteInt16(int16(len(columns)))
  981. for i, col := range columns {
  982. colType := ""
  983. if i < len(columnTypes) {
  984. colType = columnTypes[i]
  985. }
  986. mb.WriteString(col)
  987. mb.WriteInt32(0) // table OID
  988. mb.WriteInt16(0) // column attribute number
  989. mb.WriteInt32(c.getOIDForType(colType)) // type OID
  990. mb.WriteInt16(c.getTypeSizeForType(colType)) // type size
  991. mb.WriteInt32(-1) // type modifier
  992. mb.WriteInt16(0) // format code (text)
  993. }
  994. return c.writeMessage(MsgRowDescription, mb.Bytes())
  995. }
  996. // sendDataRow sends a data row
  997. func (c *Connection) sendDataRow(row []interface{}, columns []string) error {
  998. mb := NewMessageBuilder()
  999. mb.WriteInt16(int16(len(row)))
  1000. for _, value := range row {
  1001. if value == nil {
  1002. mb.WriteInt32(-1) // NULL indicator
  1003. continue
  1004. }
  1005. // Convert value to string
  1006. strValue := c.valueToString(value)
  1007. mb.WriteInt32(int32(len(strValue)))
  1008. mb.WriteBytes([]byte(strValue))
  1009. }
  1010. return c.writeMessage(MsgDataRow, mb.Bytes())
  1011. }
  1012. // sendCommandComplete sends command complete message
  1013. func (c *Connection) sendCommandComplete(tag string) error {
  1014. mb := NewMessageBuilder()
  1015. mb.WriteString(tag)
  1016. return c.writeMessage(MsgCommandComplete, mb.Bytes())
  1017. }
  1018. // sendError sends an error response
  1019. func (c *Connection) sendError(severity, code, message string) error {
  1020. mb := NewMessageBuilder()
  1021. mb.AppendByte(ErrorFieldSeverity)
  1022. mb.WriteString(severity)
  1023. mb.AppendByte(ErrorFieldCode)
  1024. mb.WriteString(code)
  1025. mb.AppendByte(ErrorFieldMessage)
  1026. mb.WriteString(message)
  1027. mb.AppendByte(0) // Terminator
  1028. if err := c.writeMessage(MsgErrorResponse, mb.Bytes()); err != nil {
  1029. return err
  1030. }
  1031. // Errors must be visible promptly, including FATAL startup failures that
  1032. // are not followed by a ReadyForQuery before the connection closes.
  1033. return c.writer.Flush()
  1034. }
  1035. // writeMessage buffers a message for the connection. It does not flush, so
  1036. // callers that need to make a response visible to the client must flush at the
  1037. // appropriate protocol boundary (ReadyForQuery, an explicit Flush message, or
  1038. // an error response). Buffering amortizes the per-message syscalls that a
  1039. // result set would otherwise incur; the underlying bufio.Writer bounds memory
  1040. // use so large result sets cannot grow the buffer without limit.
  1041. func (c *Connection) writeMessage(msgType byte, data []byte) error {
  1042. if !c.quiet {
  1043. log.Printf("Sending message type=%c length=%d", msgType, len(data)+4)
  1044. }
  1045. return WriteMessage(c.writer, msgType, data)
  1046. }
  1047. // getOIDForType returns PostgreSQL OID for type
  1048. func (c *Connection) getOIDForType(typeName string) int32 {
  1049. switch strings.ToUpper(typeName) {
  1050. case "INTEGER", "INT":
  1051. return 23 // INT4OID
  1052. case "BIGINT":
  1053. return 20 // INT8OID
  1054. case "TEXT", "VARCHAR", "CHAR", "UUID":
  1055. // UUID is stored as text (SQLite-style), so it reports TEXTOID rather
  1056. // than the native PG UUID OID.
  1057. return 25 // TEXTOID
  1058. case "REAL", "FLOAT":
  1059. return 700 // FLOAT4OID
  1060. case "DOUBLE":
  1061. return 701 // FLOAT8OID
  1062. case "BOOLEAN", "BOOL":
  1063. return 16 // BOOLOID
  1064. case "BLOB":
  1065. return 17 // BYTEAOID
  1066. case "DATETIME", "TIMESTAMP":
  1067. // Datetime values are exchanged as UTC RFC3339 (ISO8601 with a timezone
  1068. // offset), which timestamptz decodes directly.
  1069. return 1184 // TIMESTAMPTZOID
  1070. case "DATE":
  1071. return 1082 // DATEOID
  1072. default:
  1073. return 25 // Default to TEXT
  1074. }
  1075. }
  1076. // getTypeSizeForType returns type size
  1077. func (c *Connection) getTypeSizeForType(typeName string) int16 {
  1078. switch strings.ToUpper(typeName) {
  1079. case "INTEGER", "INT":
  1080. return 4
  1081. case "BIGINT":
  1082. return 8
  1083. case "REAL", "FLOAT":
  1084. return 4
  1085. case "DOUBLE":
  1086. return 8
  1087. case "BOOLEAN", "BOOL":
  1088. return 1
  1089. case "DATETIME", "TIMESTAMP":
  1090. return 8
  1091. case "DATE":
  1092. return 4
  1093. default:
  1094. return -1 // Variable length
  1095. }
  1096. }
  1097. // valueToString converts a value to string
  1098. func (c *Connection) valueToString(value interface{}) string {
  1099. if value == nil {
  1100. return ""
  1101. }
  1102. // PostgreSQL's text format for bytea is \x followed by hex. Emitting that
  1103. // lets libpq/pgx decode a BLOB column (OID 17) losslessly.
  1104. if b, ok := value.([]byte); ok {
  1105. return `\x` + hex.EncodeToString(b)
  1106. }
  1107. return fmt.Sprintf("%v", value)
  1108. }
  1109. // handleVersionQuery handles SELECT version()
  1110. func (c *Connection) handleVersionQuery() error {
  1111. columns := []string{"version"}
  1112. columnTypes := []string{"TEXT"}
  1113. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1114. return err
  1115. }
  1116. row := []interface{}{"PostgreSQL 14.0 (PizzaSQL)"}
  1117. if err := c.sendDataRow(row, columns); err != nil {
  1118. return err
  1119. }
  1120. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1121. return err
  1122. }
  1123. return c.sendReadyForQuery()
  1124. }
  1125. // handleCurrentUserQuery handles SELECT current_user
  1126. func (c *Connection) handleCurrentUserQuery() error {
  1127. columns := []string{"current_user"}
  1128. columnTypes := []string{"TEXT"}
  1129. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1130. return err
  1131. }
  1132. user := c.params["user"]
  1133. if user == "" {
  1134. user = "pizzasql"
  1135. }
  1136. row := []interface{}{user}
  1137. if err := c.sendDataRow(row, columns); err != nil {
  1138. return err
  1139. }
  1140. if err := c.sendCommandComplete("SELECT 1"); err != nil {
  1141. return err
  1142. }
  1143. return c.sendReadyForQuery()
  1144. }
  1145. // handleShowCommand handles SHOW commands
  1146. func (c *Connection) handleShowCommand(sqlUpper string) error {
  1147. var value string
  1148. var name string
  1149. if strings.Contains(sqlUpper, "SERVER_VERSION") {
  1150. name = "server_version"
  1151. value = "14.0"
  1152. } else if strings.Contains(sqlUpper, "SERVER_ENCODING") {
  1153. name = "server_encoding"
  1154. value = "UTF8"
  1155. } else if strings.Contains(sqlUpper, "CLIENT_ENCODING") {
  1156. name = "client_encoding"
  1157. value = "UTF8"
  1158. } else {
  1159. // Unknown SHOW command
  1160. c.sendError("ERROR", ErrCodeFeatureNotSupported, "SHOW command not supported")
  1161. return c.sendReadyForQuery()
  1162. }
  1163. columns := []string{name}
  1164. columnTypes := []string{"TEXT"}
  1165. if err := c.sendRowDescription(columns, columnTypes); err != nil {
  1166. return err
  1167. }
  1168. row := []interface{}{value}
  1169. if err := c.sendDataRow(row, columns); err != nil {
  1170. return err
  1171. }
  1172. if err := c.sendCommandComplete("SHOW"); err != nil {
  1173. return err
  1174. }
  1175. return c.sendReadyForQuery()
  1176. }