connection.go 35 KB

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