2
0

connection.go 33 KB

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