2
0

connection.go 39 KB

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