connection.go 37 KB

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