2
0

connection.go 36 KB

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